不知道哪个部分是错的。我已成功显示视图内的复选框列表,但当它回发到控制器时,CheckBoxViewModel模型返回null。 ASP.NET MVC
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;}
}
@model CheckBoxViewModel
foreach(var item in Model.CheckBoxLists) {
@Html.CheckBoxFor(model => model.CheckBoxState, new { id = @model.CheckBoxId }):
@Html.DisplayFor(model => model.CheckBoxDescription);
}
[HttpPost]
public ActionResult EditCheckBox(int userId, CheckBoxViewModel model) {
}
答案 0 :(得分:2)
这是完整的解决方案 -
我使用了相同的ViewModels -
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
Action上创建了一些示例数据 -
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);
}
相应的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;
}
这是页面的外观 -
当我运行代码并按下按钮时,我得到如下所示的模型 -