MVC 3在IEnumerable模型视图中编辑数据

时间:2011-08-10 11:28:14

标签: asp.net html asp.net-mvc razor

我正在尝试在强类型剃刀视图中编辑项目列表。模板不允许我在单个视图中编辑对象列表,因此我将List视图与Edit视图合并。我只需要在复选框中编辑一个布尔字段。 问题是我无法将数据恢复到控制器。我该怎么做? FormCollectionViewdata?提前谢谢。

以下是代码:

型号:

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>
}

1 个答案:

答案 0 :(得分:8)

  

我该怎么做?的FormCollection?可视数据?

以上都不是,使用视图模型:

[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>