這裏有雲的完整解決方案 -
我用了你同樣的ViewModels -
public ActionResult AddQuestion()
{
CheckBoxViewModel m = new CheckBoxViewModel();
m.CheckBoxLists = new List<CheckBoxList>();
m.CheckBoxLists.Add(new CheckBoxList() { CheckBoxDescription = "Hi1", CheckBoxId = 1, CheckBoxState = true});
m.CheckBoxLists.Add(new CheckBoxList() { CheckBoxDescription = "Hi2", CheckBoxId = 2, CheckBoxState = true });
m.CheckBoxLists.Add(new CheckBoxList() { CheckBoxDescription = "Hi3", CheckBoxId = 3, CheckBoxState = true });
return View(m);
}
-
public class CheckBoxViewModel
{
public List<CheckBoxList> CheckBoxLists { get; set; }
}
public class CheckBoxList
{
public int CheckBoxId { get; set; }
public string CheckBoxDescription { get; set; }
public bool CheckBoxState { get; set; }
}
然後我就GET
行動與一些樣本數據來創建
相應的GET
查看 -
@model WebApplication1.Controllers.CheckBoxViewModel
@{
ViewBag.Title = "AddQuestion";
}
<h2>AddQuestion</h2>
@using (Html.BeginForm("EditCheckBox", "Home"))
{
for (int i = 0; i < Model.CheckBoxLists.Count; i++)
{
@Html.CheckBox(
String.Format("CheckBoxLists[{0}].CheckBoxState", i.ToString()),
Model.CheckBoxLists[i].CheckBoxState,
new { id = Model.CheckBoxLists[i].CheckBoxId })
@Html.Label(Model.CheckBoxLists[i].CheckBoxDescription)
@Html.Hidden(String.Format("CheckBoxLists[{0}].CheckBoxDescription", i.ToString()), Model.CheckBoxLists[i].CheckBoxDescription)
@Html.Hidden(String.Format("CheckBoxLists[{0}].CheckBoxId", i.ToString()), Model.CheckBoxLists[i].CheckBoxId)
}
<input type="submit" value="Click" />
}
然後最後POST
行動 -
[HttpPost]
public ActionResult EditCheckBox(int? userId, CheckBoxViewModel model)
{
return null;
}
這裏是頁面的外觀 -
![enter image description here](https://i.stack.imgur.com/7WYnb.png)
當我運行的代碼,然後點擊按鈕,我得到的模型如下圖所示 -
![enter image description here](https://i.stack.imgur.com/AfxLW.png)
你的'form'看起來像什麼? – beautifulcoder