我想創建一個表格,將包含一系列下拉列表,所有這些都從數據庫中加載。我不知道需要多少下拉列表,或者每個下拉列表在編譯時會有多少個選項。我如何建模綁定列表'<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