我有一个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();" })
}
Run Code Online (Sandbox Code Playgroud)
我SelectList所选择的值不会被转移到DropDownList.我已经调试并逐步执行代码,发现(SelectList)ViewBag.OwnerList正确评估并选择了预期值,但生成的HTML没有option选择任何标记.
谁能看到我在这里做错了什么?
更新
以下是在我的操作中如何创建SelectList:
ViewBag.OwnerList = new SelectList(ListUtils.ProductOwners(), "Key", "Value", values["OwnerList"]);
Run Code Online (Sandbox Code Playgroud)
结果具有values["OwnerList"]选定的值.
谢谢!
您没有正确使用DropDownList帮助程序.要创建下拉列表,您需要两件事:
在您的示例中,您只有这两件事中的一件(第二件).你的第一个参数被调用OwnerList,你已经ViewBag.OwnerList作为第二个参数传递.
所以:
@Html.DropDownList(
"SelectedOwnerId",
(SelectList)ViewBag.OwnerList,
new { @onchange = "this.form.submit();" }
)
Run Code Online (Sandbox Code Playgroud)
显然我会建议你使用强类型视图和视图模型.显然摆脱了弱类型的ViewBag/ViewData/ViewCrap.
首先,设计一个视图模型以满足视图的要求(从目前为止显示的是显示下拉列表):
public class OwnerViewModel
{
[DisplayName("Choose product owner: ")]
public string SelectedOwnerId { get; set; }
public IEnumerable<SelectListItem> OwnerList { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后一个控制器:
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)
{
...
}
}
Run Code Online (Sandbox Code Playgroud)
并且您有一个相应的强类型视图:
@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();" }
)
}
Run Code Online (Sandbox Code Playgroud)
在DDL中未选择所选项目的最常见原因是您已将选择列表命名为与模型相同.强类型的观点是首选,但它是精细传递的SelectList在Viewbag.在ASP.Net MVC中查看我的教程使用DropDownList框和jQuery以及我的博客Cascading DropDownList
| 归档时间: |
|
| 查看次数: |
5736 次 |
| 最近记录: |