2013-01-22 69 views
3

我的問題是如何從視圖中獲取表數據回控制器?如何從視圖中獲取表數據是asp.net mvc 4

我在我的模型類:

public class Company 
{ 
    public string Name { get; set; } 
    public int ID { get; set; } 
    public string Address { get; set; } 
    public string Town { get; set; } 
} 

和我通過公司的名單,以我的觀點是:

@model IEnumerable<MyTestApp.Web.Models.Company> 
    .... 
    @using (Html.BeginForm("Edit", "Shop")) 
    { 
    <table id="example"> 
     <thead> 
      <tr> 
       <th> 
        @Html.DisplayNameFor(model => model.Name) 
       </th> 
       <th> 
        @Html.DisplayNameFor(model => model.Address) 
       </th> 
       <th> 
        @Html.DisplayNameFor(model => model.Town) 
       </th> 
      </tr> 
     </thead> 
     <tbody> 
      @foreach (var item in Model) { 
       <tr> 
        <td> 
         @Html.EditorFor(modelItem => item.Name) 
        </td> 
        <td> 
         @Html.EditorFor(modelItem => item.Address) 
        </td> 
        <td> 
         @Html.EditorFor(modelItem => item.Town) 
        </td> 
       </tr> 
      } 
     </tbody> 
    </table> 

    <input type="submit" value="Submit" /> 
} 

,一切看起來不錯,但我不明白怎麼弄控制器中的修改數據?我用這些方法:

public ActionResult Edit(IEnumerable<Company> companies) 
    { 
     // but companies is null 
     // and ViewData.Model also is null 

     return RedirectToAction("SampleList"); 
    } 

我需要訪問修改的對象,我在做什麼錯了?

UPDATE:由於webdeveloper,我只需要使用 'for' 循環,而不是 '的foreach' 循環。正確的版本是

<tbody> 
     @for (int i = 0; i < Model.Count(); i++) { 
      <tr>     
       <td> 
        @Html.EditorFor(modelItem => modelItem[i].Name) 
       </td> 
       <td> 
        @Html.EditorFor(modelItem => modelItem[i].Address) 
       </td> 
       <td> 
        @Html.EditorFor(modelItem => modelItem[i].Town) 
       </td> 
      </tr> 
     } 
    </tbody> 

回答

1

我認爲你缺少Company的ID在你的形式,使得該模型可以正確綁定。

您應該添加這樣的:

@using (Html.BeginForm("Edit", "Shop")) 
{ 
<table id="example"> 
    <thead> 
     <tr> 
      <th> 
       @Html.HiddenFor(model => model.ID) 
       @Html.DisplayNameFor(model => model.Name) 
      </th> 
      ... 

否則你的代碼的其餘部分似乎是確定。

+0

謝謝,亞尼克,但我現在試過這個,它不適合我。 – azhidkov

相關問題