2017-03-17 70 views
0

我必須將複選框值和文本框值綁定到model.Here我正在使用模型來檢索和發佈數據。 我試過幾個選項,但它沒有奏效。將複選框和文本框綁定到視圖模型

下面是我的代碼:

@model IEnumerable<ALDS.Web.Areas.AR.Models.ReportViewModel> 

@{ 
    ViewBag.Title = "Standings"; 
} 


    <table class="table table-bordered"> 
     <thead> 
      <tr> 
       <th>LR Date</th> 
       <th>LR Line No</th> 
       <th>Issue</th> 
       <th>Correction Response</th> 
       <th>Remarks</th> 
       <th>Submission</th> 
      </tr> 
     </thead> 
     <tbody> 
      @foreach (var item in Model) 
      { 
       <tr> 
        <td> 
         @item.InsertDate 
        </td> 
        <td> 
         @item.LRLineID <a href="">View</a> 
        </td> 
        <td>Margin % incorrect</td> 
        <td><label for="cbox1">Corrected</label> <input type="checkbox" name="Corrected" value="@item.Status" />  <label for="cbox1">Neglected</label> <input type="checkbox" name="Neglected" value="@item.Status"/></td> 
        <td><input type="text" value="@item.Comments"/></td> 
        <td><a href="@Url.Action("Update","Error",Model)">Submit</a></td> 

        </tr> 
      } 
     </tbody> 
    </table> 

我要送的複選框,文本框的值到控制器。 請幫忙。

回答

2

使用MVC提供的HtmlHelpers呈現輸入。他們將確保生成的<input/>idname屬性的格式可以由MVC ModelBinder處理。

此外,要回發對象列表,請使用for循環,以便項目獲得由ModelBinder理解的索引。

將輸入包裝在<form>中以發佈到控制器。通過以下示例,當用戶單擊「提交」按鈕時,模型將發佈到「ErrorController」中的「更新」操作。 myFormClass和​​不是必需的,我只是想展示如何在需要時添加它們。

@using(Html.BeginForm("Update", "Error", FormMethod.Post, new { @class = "myFormClass", id = myFormId })) { 
    for (var i = 0; i < Model.Length; i++) { 
     @Html.LabelFor(m => m[i].Status) 
     @Html.CheckBoxFor(m => m[i].Status) 

     @Html.LabelFor(m => m[i].Comments) 
     @Html.TextAreaFor(m => m[i].Comments) // multi line 
     @Html.TextBoxFor(m => m[i].Comments) // single line 
    } 

    <button type="submit">Submit</button> 
} 

LabelFor將試圖找到在視圖模型的財產[Display(Name="some_resource_key", ResourceType = typeof(Resources))]屬性查找翻譯後的文本被用作Resources.resx標籤。

編輯正如Antoine提到的,您必須爲所有ViewModel屬性提供輸入信息,這些屬性將被回傳。您可以使用@Html.HiddenFor(m => m[i].Id)呈現<input type="hidden"/>

+3

不要忘記告訴OP把他的模型ID放在'.hidden()' –

+0

它沒有用。 :| – user3206357

+1

你沒有把表格標籤「使用表格...」? – TTCG