MVC and binding to List of Checkboxes
Posted
by Josh
on Stack Overflow
See other posts from Stack Overflow
or by Josh
Published on 2010-05-27T14:49:01Z
Indexed on
2010/05/27
14:51 UTC
Read the original article
Hit count: 159
c#
|asp.net-mvc
Here is my problem. I have a list of models that are displayed to the user. On the left is a checkbox for each model to indicate that the user wants to choose this model (in this case, we're building products a user can add to their shopping cart). The model has no concept of being chosen...it strictly has information about the product in question.
I've talked with a few other developers after having gone through and the best I could come up with is getting the formcollection and string parsing the key values to determine whether the checkbox is checked or not. This doesn't seem ideal. I was thinking there would be something more strongly bound, but I can't figure out a way to do it.
I tried creating another model that had a boolean property to represent being checked and a property of the model and passing a list of that model type to the view and creating a ActionResult on the controller that accepts a list of the new model / checked property, but it comes back null. Am I just thinking too much like web forms and should just continue on with parsing checkbox values?
Here's what I've done for wrapping the models inside a collection:
public class SelectableCollection[T] : IList[T] {}
public class SelectableTrack{
public bool IsChecked{get;set;}
public bool CurrentTrack{get;set;}
}
For the view, I inherit from
ViewPage[SelectableCollection[SelectableTrack]]
For the controller, I have this as the ActionResult:
[HttpPost]
public ActionResult SelectTracks(SelectableCollection sc) {
return new EmptyResult();
}
But when I break inside the ActionResult, the collection is null. Any reason why it isn't coming through?
© Stack Overflow or respective owner