2011-11-09 27 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