Rea*_*idy 8 c# asp.net-core-mvc tag-helpers asp.net-core
我目前正在尝试在asp.net 5中使用taghelpers.我想使用带有ViewBag列表的select标签帮助器.我放入asp-for字段的任何内容都会给我一个错误,因为它试图从IEnumerable而不是视图包中取出它.
我想替换这个:
@model IEnumerable<InvoiceIT.Models.Invoice>
@using (Html.BeginForm())
{
<p>
@Html.DropDownList("Companies", String.Empty)
<input type="submit" value="Filter" class="btn btn-default" />
</p>
}
Run Code Online (Sandbox Code Playgroud)
有了这个:
@model IEnumerable<InvoiceIT.Models.Invoice>
<form asp-controller="Invoice" asp-action="Index" method="post" class="form-horizontal" role="form">
<select asp-for="????" asp-items="ViewBag.Companies" class="form-control">
</select>
<input type="submit" value="Save" class="btn btn-default" />
</form>
Run Code Online (Sandbox Code Playgroud)
以下是我如何填充控制器中的选择列表:
ViewBag.Companies = new SelectList(await DbContext.Company.ToListAsync(), "CompanyID", "Name");
Run Code Online (Sandbox Code Playgroud)
N. *_*len 10
如果您不希望该asp-for属性Model直接从中拉出,则可以通过提供一个来覆盖该行为@.
又名:
<select asp-for="@ViewBag.XYZ">
...
</select>
Run Code Online (Sandbox Code Playgroud)
因此,基于你所说的我相信你的位成为:
@model IEnumerable<InvoiceIT.Models.Invoice>
<form asp-controller="Invoice" asp-action="Index" method="post" class="form-horizontal" role="form">
@{
SelectList companies = ViewBag.Companies;
var currentlySelectedIndex = 0; // Currently selected index (usually will come from model)
}
<select asp-for="@currentlySelectedIndex" asp-items="companies" class="form-control">
</select>
<input type="submit" value="Save" class="btn btn-default" />
</form>
Run Code Online (Sandbox Code Playgroud)
希望这有帮助!
| 归档时间: |
|
| 查看次数: |
7666 次 |
| 最近记录: |