我有一个显示复选框列表的页面,在页面上显示我的复选框我使用代码:
@foreach (var item in Model)
{
<td>
@Html.EditorFor(
model => item.IsSelected, new { htmlAttributes = new { @name = "IsSelected" } })
</td>
}
现在我的问题是当页面被渲染时,复选框的名称前缀为item,因此名称为item.IsSelected
而不是IsSelected
,因此绑定器无法将其绑定到我的ViewModel ,我尝试过设置它的名字但没有用,是否有一种方法可以保持名称相同或者使用一些技巧将它绑定到我的ViewModel而不使用普通的Html?
修改 我的ViewModel:
public int NewsLetterId { get; set; }
public string NewsLetterEmail { get; set; }
public string NewsLetterSubscriberName { get; set; }
public bool IsActive { get; set; }
public bool IsSelected { get; set; }
public int? PriCatIDfk { get; set; }
//[ForeignKey("PriCatIDfk")]
public virtual PriCat PriCat { get; set; }
public int? SecCatIDfk { get; set; }
//[ForeignKey("SecCatIDfk")]
public virtual SecCat SecCat { get; set; }
答案 0 :(得分:1)
请勿使用EditorFor
,请尝试使用CheckBoxFor
:
@for (int i = 0; i < Model.Count(); i++)
{
<td>
@Html.CheckBoxFor(x => Model[i].IsSelected)
</td>
}
您应该使用for
循环代替foreach
,因为这是在没有编辑模板的情况下为绑定创建正确名称的唯一方法。
实际上我认为这也会起作用:
@for (int i = 0; i < Model.Count(); i++)
{
<td>
@Html.EditorFor(x => Model[i].IsSelected)
</td>
}