I have an MVC view
<%@ Page Language="C#" MasterPageFile="PathToMaster" Inherits="System.Web.Mvc.ViewPage<ModelData>" %>
and I have a form with HTML markup for a set of checkboxes:
<label for="MyCheckbox">Your choice</label>
<input type="checkbox" id="Option1" class="checkbox" name="MyCheckbox" value="Option one" />
<label for="Option1">Option one</label><br />
<input type="checkbox" id="Option2" class="checkbox" name="MyCheckbox" value="Option two" />
<label for="Option2">Option two</label><br />
and I have a controller-action pair
class MyController : Controller {
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult RequestStuff( ModelData data )
{
}
}
and that action is invoked when the form is submitted.
How do I map the checkboxes onto members of ModelData (and what members I have to add to ModelData) so that when the form is submitted data stores information on which checkboxes are checked?
OK, this one will be for MVC3, but – save for syntax changes – should work in MVC2 too. The approach is essentially the same.
First of all, you should prepare an appropriate (view)model
Then you pass this model to the view you’re showing (controller):
with the form:
Now here the HTML helpers (all the
CheckBoxFor,LabelFor,EditorForetc) allow to bind the data to the model properties.Now mind you, an
EditorForwhen the property is of typeboolwill give you the check-box in the view, too. 🙂And then, when you submit to the controller, it will auto-bind the values: