I'm trying to edit a list of items in a strongly-typed razor view. The templates don't give me the option to edit a list of objects in a single view so I merged the List view with the Edit view. I only need to edit one boolean field in a checkbox.
The problem is that i cant get the data back to the controller. How do i do it? FormCollection
? Viewdata
? Thanks in advance.
Here's the code:
Models:
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; }
}
Controller Actions:
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");
}
View:
@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>
}
How do i do it? FormCollection? Viewdata?
None of the above, use the view model:
[HttpPost]
public ActionResult EditPermissoes(IEnumerable<Permissao> model)
{
// loop through the model and for each item .HasPermissao will contain what you need
}
And inside your view instead of writing some loops use editor templates:
<table>
<tr>
<th></th>
<th>
Indicador
</th>
<th>
Nome
</th>
<th>Descrição</th>
<th></th>
</tr>
@Html.EditorForModel()
</table>
and inside the corresponding editor template (~/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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With