I have a viewmodel which contains an Episode and a boolean “watched”:
public class WatchedEpisodeViewModel
{
public Episode Episode { get; set; }
public bool Watched { get; set; }
}
I have a list of these bound to my view:
@model IEnumerable<Seriebeheer.Web.Models.WatchedEpisodeViewModel>
I’m listing this information:
@foreach (var episode in Model)
{
<tr>
<td>@episode.Episode.ID</td>
<td>@episode.Episode.Name</td>
<td>@episode.Episode.Date.Value.ToString("dd/MM/yyyy")</td>
<td><input type="checkbox" value="@episode.Episode.ID" checked="@episode.Watched"/></td>
</tr>
}
The user can mark the checkboxes and press a button to submit the info. I’d like to get to see in my controller which checkboxes are marked and which are not.
What’s the best way to achieve this?
EDIT:
[HttpPost]
public ActionResult Checkin(IEnumerable<WatchedEpisodeViewModel> episodes)
{
foreach (WatchedEpisodeViewModel episode in episodes) <-- nullreference exception
{
if (episode.Watched)
{
// test
}
}
return RedirectToAction("Index", "Home");
}
The problem is that you’re using a
foreachloop and not aforloop. You need to use aforloop because that will give the correct index to each of the fields to allow the model binder to do it’s stuff.Another of your problems, is you need to do
CheckBoxForon theWatchedbool in your model.Your final problem, is you haven’t got any
HiddenFors for your Episode fields, so when you post, you won’t know what’s been watched as the Episode on each of the items in the model will benullTry this instead: