Reputation: 1404
I have 12 checkboxes in my View and when I select some of the items and press the submit button the formcollection only has two keys [0] "IsSelected" and [1] "Playlists".
Here is my View. It is not strongly typed to a model and it is a partial view.
@using (Html.BeginForm()) {
<p>Tracks</p>
foreach (Sem_App.Models.Track track in ViewBag.Tracks)
{
@Html.CheckBoxFor(m => track.IsSelected)
@track.Title
}
@Html.DropDownList("Playlists", String.Empty)
<input type="submit" value="Add To Playlist" />
}
Controller
[HttpPost]
public ActionResult Search(String criteria, FormCollection collection)
{
}
Is there any way I can fix that? or is there a better way to pass the updated ViewBag.Tracks list to the controller? as I have a bool IsSelected Field for each track
Upvotes: 1
Views: 1842
Reputation: 712
The checkbox form items need unique name/id properties to come through correctly as a list in the POST ActionResult. Most of the examples I have seen use an index property to assign names of the input elements like so:
@using (Html.BeginForm()) {
<p>Tracks</p>
int index = 0;
foreach (Stackoverflow.Controllers.Track track in ViewBag.Tracks)
{
@Html.CheckBox("tracks[" + index + "].IsSelected", track.IsSelected)
@Html.Hidden("tracks[" + index + "].Title", track.Title)
@track.Title
index++;
}
@Html.DropDownList("Playlists", String.Empty)
<input type="submit" value="Add To Playlist" />
}
Then it would come through on POST method like this:
[HttpPost]
public ActionResult Search(String criteria, string PlayLists, List<Track> tracks)
{
}
Upvotes: 3