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?
You don’t want to bind the entire page to the collection.
MyViewModel(or whatever makes sense, use the name of the View in the name.) Make that class the basis of your strongly-typed View.SelectableCollection<T>as a property of the ViewModel (call it SelectedProducts or whatever,) and populate it in the Controller.Also, are you using a custom CheckBoxList helper? There is not one out-of-the-box with ASP.NET MVC. Use this post to build your checkboxes:
How to handle checkboxes in ASP.NET MVC forms?