我想创建一个表格,将包含一系列下拉列表,所有这些都从数据库中加载。我不知道需要多少下拉列表,或者每个下拉列表在编译时会有多少个选项。我如何建模绑定列表'<SelectItem>'使用MVC.Net
这些字段如何设置以允许它们在发布时建模?
下面的每个代码元素都有很多其他复杂性,但即使降低到基本级别,我也无法使模型绑定正常工作。
型号:
public class MyPageViewModel
{
public List<MyDropDownListModel> ListOfDropDownLists { get; set; }
}
public class MyDropDownListModel
{
public string Key { get; set; }
public string Value { get; set; }
public List<SelectListItem> Options { get; set; }
}
的控制器获取操作:
[AcceptVerbs(HttpVerbs.Get)]
[ActionName("MyAction")]
public ActionResult MyGetAction()
{
var values_1 = new List<string> {"Val1", "Val2", "Val3"};
var options_1 =
values_1
.ConvertAll(x => new SelectListItem{Text=x,Value=x});
var myDropDownListModel_1 =
new MyDropDownListModel { Key = "Key_1", Options = options_1 };
var values_2 = new List<string> {"Val4", "Val5", "Val6"};
var options_2 =
values_2
.ConvertAll(x => new SelectListItem{Text=x,Value=x})};
var myDropDownListModel_2 =
new MyDropDownListModel { Key = "Key_2", Options = options_2 };
var model =
new MyPageViewModel
{
ListOfDropDownLists =
new List<MyDropDownListModel>
{
myDropDownListModel_1,
myDropDownListModel_2,
}
};
return View(model);
}
的控制器POST操作:
[AcceptVerbs(HttpVerbs.Post)]
[ActionName("MyAction")]
public ActionResult MyPostAction(MyPageViewModel model)
{
//Do something with posted model...
//Except 'model.ListOfDropDownLists' is always null
return View(model);
}
的观点:
@model MyPageViewModel
@using (Html.BeginForm("MyPostAction"))
{
foreach (var ddl in Model.ListOfDropDownLists)
{
@Html.DropDownListFor(x => ddl.Value, ddl.Options)
}
<button type="submit">Submit</button>
}
编辑:更正了拼写错误和复制粘贴错误。
解:
问题被证明是在视图中在foreach环。将其更改为for-loop会导致帖子按预期填充。更新的观点是如下:
@using (Html.BeginForm("MyPostAction"))
{
for (int i = 0; i < Model.ListOfDropDownLists.Count; i++)
{
@Html.HiddenFor(x => x.ListOfDropDownLists[i].Key)
@Html.DropDownListFor(m => m.ListOfDropDownLists[i].Value, Model.ListOfDropDownLists[i].Options);
}
<button type="submit">Submit</button>
}
你有什么错误吗? –
@ user256103不会发生错误。当我在post操作中的断点处调试时,模型属性“MyPageViewModel.ListOfDropDownLists”为null。 – Gifreakius