从ViewBag中选择TagHelper Using List
本文关键字:Using List TagHelper 选择 ViewBag | 更新日期: 2023-09-27 18:06:09
我正在尝试在asp.net 5中使用标签助手。我想使用一个选择标签助手与一个列表从ViewBag。我放入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>
}
与这个:@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>
下面是我在控制器中填充选择列表的方法:
ViewBag.Companies = new SelectList(await DbContext.Company.ToListAsync(), "CompanyID", "Name");
如果您不希望asp-for
属性直接从Model
中提取,您可以通过提供@
来覆盖该行为。
又名:
<select asp-for="@ViewBag.XYZ">
...
</select>
因此,根据你所说的,我相信你的位变成了:
@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>
希望这对你有帮助!
asp-for只需要是当前选定值的属性,而asp-items需要是
IEnumerable<SelectListItem>
这个片段来自我的项目中的工作代码:
<select id="CompanyCountry" asp-for="CompanyCountry"
asp-items="Model.AvailableCountries" class="form-control"></select>
在我的模型中,我使用
IList<SelectListItem>
for AvailableCountries
你可以这样尝试…
@Html.DropDownListFor(model => model.Id_TourCategory, new SelectList(ViewBag.TourCate, "Value", "Text"))
public ActionResult TourPackage()
{
List<TourCategory> lst = new List<TourCategory>();
lst = db.TourCategories.ToList();
ViewBag.TourCate = new SelectList(lst, "Id", "CategoryName");
return View();
}