我有一个带有下拉列表的 Razor 页面:
@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 没有选择任何 option
标记。谁能看到我在这里做错了什么?
更新
以下是在我的操作中创建 SelectList 的方式:
ViewBag.OwnerList = new SelectList(ListUtils.ProductOwners(), "Key", "Value", values["OwnerList"]);
结果具有选择的
values["OwnerList"]
指示的值。谢谢!
最佳答案
您没有正确使用 DropDownList 帮助程序。为了创建下拉列表,您需要两件事:
在您的示例中,您只有这两件事中的一件(第二件)。您的第一个参数称为
OwnerList
并且您将 ViewBag.OwnerList
作为第二个参数传递。所以:
@Html.DropDownList(
"SelectedOwnerId",
(SelectList)ViewBag.OwnerList,
new { @onchange = "this.form.submit();" }
)
显然,我会建议您使用强类型 View 和 View 模型。并且显然摆脱了弱类型的 ViewBag/ViewData/ViewCrap。
因此,首先设计一个 View 模型以满足您的 View 的要求(从您目前所展示的内容来看,它是显示一个下拉列表):
public class OwnerViewModel
{
[DisplayName("Choose product owner: ")]
public string SelectedOwnerId { get; set; }
public IEnumerable<SelectListItem> OwnerList { get; set; }
}
然后是一个 Controller :
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)
{
...
}
}
并且您有一个相应的强类型 View :
@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();" }
)
}
关于asp.net-mvc - SelectList 选定的值未结转到 DropDownList,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9269037/