首先,@Html.CheckboxFor(m => m.Checkbox, "Product 1")
分配"Product 1"
为 html 属性并将呈现<input length="9" type="checkbox" .../>
(已添加长度属性,其值等于文本中的字符数)。由于重复的id
属性,它还创建了无效的 html。并且该[Required]
属性是没有意义的(布尔值要么是真要么是假,并且总是需要的)。目前您在复选框和产品之间没有任何关系。
您应该创建一个视图模型来表示您想要显示的内容
public class ProductVM
{
public bool IsSelected { get; set; }
public string Code { get; set; }
public string Name { get; set; }
}
控制器
public ActionResult Edit()
{
List<ProductVM> model = new List<ProductVM>()
{
new ProductVM() { Code = "Product 1", Name = "Apple" },
new ProductVM() { Code = "Product 2", Name = "Banana" },
new ProductVM() { Code = "Product 3", Name = "Grapes"}
};
return View(model);
}
[HttpPost]
public ActionResult Edit(List<ProductVM> model)
{
foreach(ProductVM item in model)
{
if (item.IsSelected)
{
string code = item.Code;
string name= item.Name;
}
}
}
看法
@model List<ProductVM>
@using(Html.BeginForm())
{
for(int i = 0; i < Model.Count; i++)
{
@Html.HiddenFor(m => m[i].Code)
@Html.HiddenFor(m => m[i].Name)
@Html.CheckBoxFor(m => m[i].IsSelected)
@Html.LabelFor((m => m[i].IsSelected, Model[i].Name)
}
<input type="submit" />
}
如果您想要客户端验证,您将不得不编写自己的验证属性来实现IClientValitable
和编写相关的 jquery 验证方法(但这是一个单独问题的主题)