2014-02-11 77 views
0

我使用下面的代碼:在HTTP POST方法無效獲取響應

控制器:

public ActionResult Update(int studentId = 0, int subjectId = 0) 
     { 
      Engine engine = new Engine(studentId, subjectId); 
      List<Chapter> chapterList = engine.GetChapters(); 

      return View(chapterList); 
     } 

     [HttpPost] 
     public ActionResult Update(List<Chapter> model)  
     {   

      return View(model); 
     } 

Update.cshtml:

@model IEnumerable<Chapter> 
@{ 
    ViewBag.Title = "Update"; 
} 
<h2> 
    Update</h2> 
@using (Html.BeginForm("Update", "StudyPlan", FormMethod.Post)) 
{ 
    <fieldset> 
     <table> 
      @foreach (var item in Model) 
      { 

       <tr> 
        <td> 
         @item.name 
        </td> 
        <td> 
         @Html.CheckBoxFor(chapterItem => item.included) 
        </td> 
       </tr> 
      } 
     </table> 
     <input type="submit" value="submit" /> 
    </fieldset> 


} 

我想,當用戶選擇複選框,響應應該出現在控制器的httppost方法中。但我得到空值更新方法。我是否做錯了

+0

請問你的'chapter'模型? – Zafar

回答

0

您需要使用for而不是foreach。在這種情況下複選框將被呈現爲

<input type='checkbox' name='Model[0].included'/> 
<input type='checkbox' name='Model[1].included'/> 
... 

然後ModelBinder的將成功地創建模型

實施例:

@model List<Chapter> 
@{ 
    ViewBag.Title = "Update"; 
} 
<h2> 
    Update</h2> 
@using (Html.BeginForm("Update", "StudyPlan", FormMethod.Post)) 
{ 
    <fieldset> 
     <table> 
      @for (int i =0;i<Model.Count;i++) 
      { 

       <tr> 
        <td> 
         @Model[i].name 
        </td> 
        <td> 
         @Html.CheckBoxFor(chapterItem => Model[i].included) 
        </td> 
       </tr> 
      } 
     </table> 
     <input type="submit" value="submit" /> 
    </fieldset> 


} 

PS。在該示例中,模型從IEnumerable變爲List<>

這是因爲MVC在CheckBoxFor方法中分析表達式。而它這個表達式是數組訪問器,那麼它會生成不同的控件名稱。而基於名稱ModelBinder的成功創建List<>

+0

現在,屬性'name'和'id'即將變爲null,如何解決這個問題? – Jaguar

+0

它們是空的,因爲你沒有任何輸入元素。如果你想在模型中接收它們,你需要添加它們。您可以將它們添加爲'Html.HiddenFor(m => Model [i] .id)'和'Html.HiddenFor(m => Model [i] .name)'。 MVC根據頁面上的輸入\ textarea字段創建模型對象。 –

0

正如謝爾蓋建議,使用for循環,但試試這個:

@for (int i =0;i<Model.Count;i++) 
{ 

    <tr> 
     <td> 
      @Html.HiddenFor(m => m[i].id) 
      @Html.DisplayFor(m => m[i].name) 
     </td> 
     <td> 
      @Html.CheckBoxFor(m => m[i].included) 
     </td> 
    </tr> 
}