如何使用模型在控制器中获取选中的复选框

How to get selected checkbox in a controller using model

我正在尝试使用模型获取所选复选框的值,但无法如我所愿地获取;

下面是 table 图片

下面是我为这个视图编写的代码

下面是result.I获取空值

的代码

下面是我的模型声明

public class RoleDetail
  {
    [Key]
    public int RoleDetailID { get; set; }

    public bool IsCreate { get; set; }
    public bool IsDelete { get; set; }
    public bool IsView { get; set; }
    public bool IsEdit { get; set; }
    public bool IsDownload { get; set; }
    public string ControllerName { get; set; }
    public System.DateTime CreateDate { get; set; }
    public Int32 UserTypeId { get; set; }
}
public enum ControllerName
{
    Account, Candidate, Career, ChooseUs, ContactUs, DocumentType, Employee, Gallery, GalleryType, GetTouch, Home, JobCategory, Jobs, Portfolio, ResumeUpload, RoleDetail, Services, User, UserRoleType

}

将您视图中的 foreach 循环替换为 for:

@for (var i = 0; i < lst.Count; i++)
{
    ...
    @Html.CheckBoxFor(x => lst[i].IsCreate)
    @Html.CheckBoxFor(x => lst[i].IsView)
    @Html.CheckBoxFor(x => lst[i].IsDelete)
    ...
}

要使其正常工作,请确保您迭代的变量是 IList<T>T[]

您的控制器操作参数也应相应命名:

public ActionResult Create(IEnumerable<RoleDetail> lst)
{
    ...
}

您不应在视图中创建 RoleDetail。在 GET 方法中创建一个 List<RoleDetail>,用您要显示的对象填充它并 return 它到视图。

控制器

public ActionResult Create()
{
  List<RoleDetail> model = new List<RoleDetail>();
  // populate the collection, for example
  foreach(var name in Enum.GetNames(typeof(ControllerName)))
  {
    model.Add(new RoleDetail()
    {
      ControllerName = name,
      IsCreate = true // etc
    });
  }  
  return View(model);
}

public ActionResult Create(IEnumerable<RoleDetail> model)
{
}

查看

@model List<RoleDetail>
@using(Html.BeginForm())
{
  for(int i = 0; i < Model.Count; i++)
  {
    @Html.HiddenFor(m => m.ControllerName) // needed for postback
    @Html.DisplayFor( => m.ControllerName)
    @Html.CheckBoxFor(m => m.IsCreate)
    ....
  }
  <input type="submit" />
}

旁注

  1. 不要尝试覆盖 name(或 value)属性。 html 助手为模型绑定正确设置这些(无论如何你 只是将它设置为助手生成的值)
  2. foreach 循环不起作用的原因是您生成 重复的 name 属性(并且由于重复而无效 html id 个属性)。 for 循环正确生成正确的 带索引的名称(例如 <input name="[0].IsCreate " ..><input name="[1].IsCreate " ..>
  3. 您似乎没有为所有模型渲染控件 属性,所以使用只包含那些属性的视图模型 需要display/edit。 What is a view model in MVC
  4. 你有 public enum ControllerName 所以我怀疑 属性 RoleDetail 中的 ControllerName 应该是 public ControllerName ControllerName { get; set; }?

将来,post 代码,而不是它的图像!