我有一个Razor页面,其中包含一个表单内的下拉列表: @using (Html.BeginForm("ProductsByOwners", "Report", FormMethod.Post, new { @id = "ProductsByOwners" })){ @Html.Label("Choose product owner: ") @Html.DropDownList("OwnerL
@using (Html.BeginForm("ProductsByOwners", "Report", FormMethod.Post, new { @id = "ProductsByOwners" })) { @Html.Label("Choose product owner: ") @Html.DropDownList("OwnerList", (SelectList)ViewBag.OwnerList, new { @onchange = "this.form.submit();" }) }
我的SelectList的选定值未被转移到DropDownList.我调试并逐步完成代码,发现(SelectList)ViewBag.OwnerList正确评估并选择了预期值,但生成的HTML没有选择任何选项标签.
谁能看到我在这里做错了什么?
更新
以下是在我的操作中如何创建SelectList:
ViewBag.OwnerList = new SelectList(ListUtils.ProductOwners(), "Key", "Value", values["OwnerList"]);
结果具有由值[“OwnerList”]指示的值.
谢谢!
您没有正确使用DropDownList帮助程序.要创建下拉列表,您需要两件事:>提交表单时绑定到所选值的标量属性
>将选项绑定到的集合
在您的示例中,您只有这两件事中的一件(第二件).您的第一个参数称为OwnerList,并且您将ViewBag.OwnerList作为第二个参数传递.
所以:
@Html.DropDownList( "SelectedOwnerId", (SelectList)ViewBag.OwnerList, new { @onchange = "this.form.submit();" } )
显然我会建议你使用强类型视图和视图模型.显然摆脱了弱类型的ViewBag / ViewData / ViewCrap.
首先,设计一个视图模型以满足视图的要求(从目前为止显示的是显示下拉列表):
public class OwnerViewModel { [DisplayName("Choose product owner: ")] public string SelectedOwnerId { get; set; } public IEnumerable<SelectListItem> OwnerList { get; set; } }
然后一个控制器:
public class ReportController: Controller { public ActionResult ProductsByOwners() { var model = new OwnerViewModel { // preselect the second owner SelectedOwnerId = "2", // obviously those come from your database or something OwnerList = new[] { new SelectListItem { Value = "1", Text = "owner 1" }, new SelectListItem { Value = "2", Text = "owner 2" }, new SelectListItem { Value = "3", Text = "owner 3" }, } }; return View(model); } [HttpPost] public ActionResult ProductsByOwners(OwnerViewModel model) { ... } }
并且您有一个相应的强类型视图:
@model OwnerViewModel @using (Html.BeginForm("ProductsByOwners", "Report", FormMethod.Post, new { id = "ProductsByOwners" })) { @Html.LabelFor(x => x.SelectedOwnerId) @Html.DropDownListFor( x => x.SelectedOwnerId, Model.OwnerList, new { onchange = "this.form.submit();" } ) }