如何在控制器中获取多个值的动态复选框

本文关键字:动态 复选框 获取 控制器 | 更新日期: 2023-09-27 18:24:56

这里我正在创建一个具有动态元素的表单。我需要将Name属性分配给checkbox,否则我尝试了,但我会出错。

Index.cshtml:

 @using (Html.BeginForm("Index", "Home", FormMethod.Post))
 {
     for (int i = 0; i <= Model.userDetails.Count; i++)
     {
        @Html.CheckBoxFor(Model.userDetails[i].Name);    // Error  occurs here
     }
      @Html.TextBoxFor(x=>x.FullName);
        <input type="submit" id="btnSubmit" value="Submit" />
 } 

控制器:

public ActionResult Index()
{
    FetchDetails objFetch = new FetchDetails();
    ItemsModel objModel = new ItemsModel();
    objModel.userDetails = objFetch.setPersonDetails();
    objModel.FullName = "Sam Anderson";
    return View(objModel);
}
[HttpPost]
public ActionResult Index(ItemsModel model)   // I can able to get value for textbox in the "model" 
{
    return View();
}

型号:

public class ItemsModel
{
   public List<person> userDetails { get; set; }
   public string FullName { get; set; }
}
public class person
{
    public string Name { get; set; }
    public bool Enabled { get; set; }
    public int Age { get; set; }
}
public class FetchDetails
{
 public List<person> setPersonDetails()
 {
    List<person> objPerson = new List<person>();
    person per = null;
    per = new person();
    per.Age = 25;
    per.Enabled = true;
    per.Name = "Viki";
    objPerson.Add(per);
    per = new person();
    per.Age = 25;
    per.Enabled = true;
    per.Name = "Sam";
    objPerson.Add(per);
    per = new person();
    per.Age = 23;
    per.Enabled = false;
    per.Name = "Anderson";
    objPerson.Add(per);
    per = new person();
    per.Age = 21;
    per.Enabled = false;
    per.Name = "Mike";
    objPerson.Add(per);
    return objPerson;
  }
}

错误:

Compiler Error Message: CS1928: 'System.Web.Mvc.HtmlHelper<DynamicCheckBoxMVC.Models.ItemsModel>' does not contain a definition for 'CheckBoxFor' and the best extension method overload 'System.Web.Mvc.Html.InputExtensions.CheckBoxFor<TModel>(System.Web.Mvc.HtmlHelper<TModel>, System.Linq.Expressions.Expression<System.Func<TModel,bool>>)' has some invalid arguments

如何在控制器中获取多个值的动态复选框

试试这个,

在不绑定任何模型实体的情况下,不能使用CheckBoxFor。请参阅下面的代码。

for (int i = 0; i <= Model.userDetails.Count; i++)
     {
        @Html.CheckBox(Model.userDetails[i].Name);    // Error  occurs here
     }