MVC Post动作没有从列表中获取任何数据< >对象
本文关键字:任何 获取 数据 对象 列表 Post MVC | 更新日期: 2023-09-27 18:02:14
我有问题从列表中接收数据,当在Chrome中看到它看起来很好,因为有所有值,但在Visual Studio调试它不正确,它填充列表项,但不是值。我做错了什么?
模型:
public class PermisoModel
{
public int Id;
public string Name;
public bool Checked;
}
public class ModuloModel
{
public int Id;
public string Name;
public List<PermisoModel> Permisos { get; set; }
}
控制器:
public ActionResult Permisos(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Usuario usuario = db.Usuario.FirstOrDefault(x => x.id_usuario == id && x.usu_estado == true);
if (usuario == null)
{
return HttpNotFound();
}
List<ModuloModel> ModuloModel = db.Modulo.Where(mod => mod.mod_estado == true).Select(mod => new ModuloModel {
Id = mod.id_modulo,
Name = mod.mod_nombre,
Permisos = db.Permiso.Where(per => per.id_modulo == mod.id_modulo && per.per_estado == true).Select(x => new PermisoModel { Id = x.id_permiso, Name = x.id_permiso + " - " + x.per_nombre, Checked = db.PermisoUsuario.Count(y => x.id_permiso == y.id_permiso && y.id_usuario == usuario.id_usuario)>0 }).ToList()
}
).ToList();
return View(ModuloModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Permisos(int? id, List<ModuloModel> model)
{
return View(model);
}
视图:
@model List<ModuloModel>
@using Data.Models
@using (Html.BeginForm())
{
<p class="btn-group pull-right">
<a href="@Url.Action("Index")" class="btn btn-default">
<i class="glyphicon glyphicon-menu-left"></i>
Volver
</a>
<button type="submit" class="btn btn-warning"><i class="glyphicon glyphicon-pencil"></i> Editar</button>
</p>
<hr style="clear:both;" />
@Html.AntiForgeryToken()
for (int x = 0; x < Model.Count; x++)
{
<fieldset class="form-horizontal">
@Html.HiddenFor(model => model[x].Id)
<legend>@Model[x].Name</legend>
@for (int y = 0; y < Model[x].Permisos.Count; y++)
{
<div class="form-group">
<label>
@Html.HiddenFor(model => model[x].Permisos[y].Id)
@Html.CheckBoxFor(model => model[x].Permisos[y].Checked)
@Html.DisplayFor(model => model[x].Permisos[y].Name)
</label>
</div>
}
</fieldset>
}
}
提前感谢!
为了让模型绑定器将发布的表单数据映射到HttpPost操作方法的参数,你的viewmodel/dto类属性应该是带有set
和get
访问器的公共属性
您当前的代码没有set
访问器。因此,模型绑定器不能为它设置值(来自发布的表单数据)。
应该可以。
public class PermisoModel
{
public int Id { set; get; }
public string Name { set; get; }
public bool Checked { set; get; }
}
public class ModuloModel
{
public int Id { set; get; }
public List<PermisoModel> Permisos { get; set; }
}