Asp.net

MVC 3 在 IEnumerable 模型視圖中編輯數據

  • April 16, 2013

我正在嘗試在強類型剃刀視圖中編輯項目列表。模板沒有讓我選擇在單個視圖中編輯對象列表,因此我將列表視圖與編輯視圖合併。我只需要在復選框中編輯一個布爾欄位。問題是我無法將數據返回給控制器。我該怎麼做?FormCollection? Viewdata? 提前致謝。

這是程式碼:

楷模:

public class Permissao
{
   public int ID { get; set; }
   public TipoPermissao TipoP { get; set; }
   public bool HasPermissao { get; set; }
   public string UtilizadorID { get; set; }
}

public class TipoPermissao
{
   public int ID { get; set; }
   public string Nome { get; set; }
   public string Descricao { get; set; }
   public int IndID { get; set; }
}

控制器動作:

   public ActionResult EditPermissoes(string id)
   {
       return View(db.Permissoes.Include("TipoP").Where(p => p.UtilizadorID == id));
   }

   [HttpPost]
   public ActionResult EditPermissoes(FormCollection collection)
   {
       //TODO: Get data from view
       return RedirectToAction("GerirUtilizadores");
   }

看法:

@model IEnumerable<MIQ.Models.Permissao>

@{
   ViewBag.Title = "EditPermissoes";
}

@using (Html.BeginForm())
{
   <table>

   <tr>
       <th></th>
       <th>
           Indicador
       </th>
       <th>
           Nome
       </th>
       <th>Descrição</th>
       <th></th>
   </tr>
   @foreach (var item in Model) {
       <tr>
           <td>
               @Html.CheckBoxFor(modelItem => item.HasPermissao)
           </td>
           <td>
               @Html.DisplayFor(modelItem => item.TipoP.IndID)
           </td>
           <td>
               @Html.DisplayFor(modelItem => item.TipoP.Nome)
           </td>
           <td>
               @Html.DisplayFor(modelItem => item.TipoP.Descricao)
           </td>
       </tr>
   }
</table> 
<p>
  <input type="submit" value="Guardar" />
</p>
}

我該怎麼做?表單集合?查看數據?

以上都不是,使用視圖模型:

[HttpPost]
public ActionResult EditPermissoes(IEnumerable<Permissao> model)
{
   // loop through the model and for each item .HasPermissao will contain what you need
}

在您的視圖中,而不是編寫一些循環,使用編輯器模板:

<table>
   <tr>
       <th></th>
       <th>
           Indicador
       </th>
       <th>
           Nome
       </th>
       <th>Descrição</th>
       <th></th>
   </tr>
   @Html.EditorForModel()
</table> 

並在相應的編輯器模板 ( ~/Views/Shared/EditorTemplates/Permissao.cshtml) 中:

@model Permissao
<tr>
   <td>
       @Html.CheckBoxFor(x => x.HasPermissao)
   </td>
   <td>
       @Html.DisplayFor(x => x.TipoP.IndID)
   </td>
   <td>
       @Html.DisplayFor(x => x.TipoP.Nome)
   </td>
   <td>
       @Html.DisplayFor(x => x.TipoP.Descricao)
   </td>
</tr>

引用自:https://stackoverflow.com/questions/7010038