0

Here I am creating a form with dynamic elements. I need to assign the Name property to checkboxfor I tried but Iam getting error.

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

Controller:

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();
}

Model:

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

Error:

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
4

1 回答 1

0

尝试这个,

如果不绑定模型的任何实体,就不能使用 CheckBoxFor。请看下面的代码。

for (int i = 0; i <= Model.userDetails.Count; i++)
     {
        @Html.CheckBox(Model.userDetails[i].Name);    // Error  occurs here
     }
于 2013-07-26T05:47:15.277 回答