我有一个Index.cshtml视图:
@model AttendenceModel
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
@using (Html.BeginForm("VisOppsummering", "Attendences", new { AttendenceModel = Model }, FormMethod.Post))
{
@Html.DisplayFor(m => m.ClassName)
@Html.EditorFor(m => m.Attendences)
<button type="submit">Next</button>
}
和编辑模板Attendence.cshtml:
@model Attendence
@Html.DisplayFor(m => m.Student.Name)
@Html.RadioButtonFor(m => m.Attended, true, new { id = "attendence" })
教师可以检查所有上过学的学生,然后将更改的模型传递给“审核”操作,以便他们可以审核所有受访和未参加的学生并提交。我想为此使用MVC最佳实践。 AttendenceModel有几个属性和一个通用列表Attendences是List。
我尝试过没有成功。模型是空的。:
[HttpPost]
public ActionResult Review(AttendenceModel model)
{
if (TryUpdateModel(model))
{
return View(model);
}
}
答案 0 :(得分:0)
BeginForm
助手的以下论点毫无意义:
new { AttendenceModel = Model }
你无法传递像这样的复杂对象。只有简单的标量值。您可以在表单中使用隐藏字段,用于无法编辑的所有属性和另一个可见的输入字段。甚至更好:使用一个视图模型,它只包含可以在表单上编辑的属性和一个额外的id,它允许您从数据库中获取原始模型,并使用TryUpdateModel
方法仅更新属性这是POST请求的一部分:
[HttpPost]
public ActionResult Review(int id)
{
var model = Repository.GetModel(id);
if (TryUpdateModel(model))
{
return View(model);
}
...
}
就观点而言,它将成为:
@model AttendenceViewModel
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
@using (Html.BeginForm("Review", "SomeControllerName"))
{
@Html.HiddenForm(x => x.Id)
@Html.DisplayFor(m => m.ClassName)
@Html.EditorFor(m => m.Attendences)
<button type="submit">Next</button>
}