简体   繁体   English

使用选择框显示数据的 Linq 查询

[英]Linq query using select box to display data

我正在尝试实现一个 linq 查询,它允许用户选择例如显示在选择框中的 1-10,并根据用户单击的那个显示相应的“CarID”。

You could refer to the below working example:您可以参考以下工作示例:

1.Model 1.型号

public class Car
{
    public int CarID { get; set; }

    public string Model { get; set; }
    public string Manufacturer { get; set; }
    public string EngineSize { get; set; }

}

2.PageModel: 2.页面模型:

 public class Query1Model : PageModel
{
    private readonly RazorPageDbContext _context;

    public Query1Model(RazorPageDbContext context)
    {
        _context = context;
    }

    public IList<Car> CarID { get; set; }
    public List<SelectListItem> Options { get; set; }
    [BindProperty(SupportsGet =true)]
    public int SearchCarID { get; set; }

    public async Task<IActionResult> OnGetAsync()
    {
        Options = _context.Cars.Select(a =>
                             new SelectListItem
                             {
                                 Value = a.CarID.ToString(),
                                 Text = a.CarID.ToString()
                             }).ToList();

        if (SearchCarID != 0)
        {
            var CarQuery = (from s in _context.Cars
                            where s.CarID == SearchCarID
                            select s);
            CarID = await CarQuery.ToListAsync();
        }
        else
        {
            CarID = await _context.Cars.ToListAsync();
        }
        return Page();
    }
 }

3.Razor Page: 3.剃须刀页面:

<h2>Filter By CarID</h2>

<form>
<p>
    Select the CarID you wish to display:
    <select asp-for="SearchCarID" asp-items="@Model.Options">
        <option value="">Pick one</option>
    </select>
    <input type="submit" value="Find" />
</p>
</form>

<h3> Here is the CarIDs you requested</h3>
<table class="table">
<thead>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.CarID[0].CarID)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.CarID[0].Model)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.CarID[0].Manufacturer)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.CarID[0].EngineSize)
        </th>
    </tr>
</thead>
<tbody>
    @foreach (var item in Model.CarID)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelitem => item.CarID)
            </td>
            <td>
                @Html.DisplayFor(modelitem => item.Model)
            </td>
            <td>
                @Html.DisplayFor(modelitem => item.Manufacturer)
            </td>
            <td>
                @Html.DisplayFor(modelitem => item.EngineSize)
            </td>
        </tr>
    }
</tbody>
</table>

4.Result: 4.结果: 在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM