I have a page that show a list of checkboxes, for showing my checkbox on page I use the code:
@foreach (var item in Model)
{
<td>
@Html.EditorFor(
model => item.IsSelected, new { htmlAttributes = new { @name = "IsSelected" } })
</td>
}
now my problem is when the page got rendereded the name of checkboxes is getting prepended with item therefore the name is item.IsSelected
instead of IsSelected
and as a result binder can't bind it to my ViewModel, I've tried setting its name but no use, is there a way I can keep the name the same or use some trick to bind it to my ViewModel without using plain Html?
Edit: My 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; }
Just don't use EditorFor
, try CheckBoxFor
instead:
@for (int i = 0; i < Model.Count(); i++)
{
<td>
@Html.CheckBoxFor(x => Model[i].IsSelected)
</td>
}
You should use for
loop instead foreach
, becouse it's only way to make right names for binding without Editor Template.
Actually i suppose this will work too:
@for (int i = 0; i < Model.Count(); i++)
{
<td>
@Html.EditorFor(x => Model[i].IsSelected)
</td>
}