这里我正在创建一个包含动态元素的表单。我需要将Name属性分配给checkboxfor我试过但我得到错误。
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
答案 0 :(得分:0)
试试这个,
如果不绑定任何模型实体,则无法使用CheckBoxFor。请参阅下面的代码。
for (int i = 0; i <= Model.userDetails.Count; i++)
{
@Html.CheckBox(Model.userDetails[i].Name); // Error occurs here
}