2013-02-02 55 views
0

我无法在此上使用一个List,只能在视图上使用whitout编辑标签,我有一个视图工作良好,但我不能编辑它们中的一个列表。在控制器上编辑IEnumerable null

@model IEnumerable<MyMixtapezServerCodeHomePage.Models.album> 
@using (Html.BeginForm("FeatureSystem", "album", FormMethod.Post)) 
{ 

<table> 

    <tr> 
     <th> 
      @Html.DisplayNameFor(model => model.name) 
     </th> 
     <th> 
      @Html.DisplayNameFor(model => model.feature) 
     </th> 
     <th> 
      @Html.DisplayNameFor(model => model.feature_order) 
     </th> 
     <th></th> 
    </tr> 

    @foreach (var item in @Model) 
    { 

     <tr> 
      <td> 

       <div class="editor-label"> 
        @Html.LabelFor(model => item.name) 
       </div> 
       <div class="editor-field"> 
        @Html.EditorFor(model => item.name,"album") 
        @Html.ValidationMessageFor(model => item.name) 
       </div> 
      </td> 
      <td> 
       <div class="editor-label"> 
        @Html.LabelFor(model => item.feature,"album") 
       </div> 
       <div class="editor-field"> 
        @Html.EditorFor(model => item.feature) 
        @Html.ValidationMessageFor(model => item.feature) 
       </div> 
      </td> 
      <td> 
       <div class="editor-label"> 
        @Html.LabelFor(model => item.feature_order) 
       </div> 
       <div class="editor-field"> 
        @Html.EditorFor(model => item.feature_order,"album") 
        @Html.ValidationMessageFor(model => item.feature_order) 
       </div> 
      </td> 
      <td></td> 
     </tr> 





    } 
    <input type="submit" /> 
</table>} 

控制器

 [HttpPost] 
    public ActionResult FeatureSystem(IEnumerable<album> albums) 
    { 
     foreach (album album in albums) 
     { 
      if (ModelState.IsValid) 
      { 
       albumRepository.Update(album); 
       albumRepository.SaveChanges(); 

      } 

     } 

     return RedirectToAction("Index"); 

    } 

我收到相册是空的,为什么?我可以编辑一个列表吗?我只需要这个。

回答

0

我相信这一点,因为MVC3

没有改变

所以有你必须使用一个for循环可编辑收藏,而不是一个foreach,或结合将无法正常工作。

@for(var i = 0; i < Model.Count; i++) 
{ 
    <tr> 
     <td> 

      <div class="editor-label"> 
       @Html.LabelFor(model => Model[i].name) 
      </div> 
      <div class="editor-field"> 
       @Html.EditorFor(model => Model[i].name,"album") 
       @Html.ValidationMessageFor(model => Model[i].name) 
      </div> 
     </td> 
     <td> 

    ... 
} 

看一看this,老了,但我觉得不过时。

2

在视图中使用IList而不是IEnumerable,并用for循环替换foreach循环。代替

使用

@model IList <MyMixtapezServerCodeHomePage.Models.album> 

@model IEnumerable<MyMixtapezServerCodeHomePage.Models.album> 

步骤2::

步骤1

使用

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

代替

@foreach (var item in @Model) 

参考How to pass IEnumerable list to controller in MVC including checkbox state?了解更多详情。