2011-11-09 96 views
0

我有一个Index.cshtml观点:MVC3:批量编辑考勤和模型传递到审查行动

@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

以下参数传送给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> 
} 
+0

非常感谢您的帮助!我的代码实际上是正确的。最初我尝试过@using(Html.BeginForm(“Review”,“Attendences”,FormMethod.Post)),但'public ActionResult Review(AttendenceModel模型)'中的模型总是空的。我所有问题的原因实际上是datatables.net。他们改变了表中所有条目的ID,因此破坏了我的模型。 – Goran