Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I map checkboxes onto MVC model members?

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?

like image 375
sharptooth Avatar asked May 18 '12 08:05

sharptooth


People also ask

How do you declare a view model?

To specify a model for the View, we can using @model statement at the top of the View page.

What goes in the model in MVC?

An MVC model contains all of your application logic that is not contained in a view or a controller. The model should contain all of your application business logic, validation logic, and database access logic.


1 Answers

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

public class MyViewModel
{
    [DisplayName("Option 1")]
    public bool Option1 { get; set; }

    [DisplayName("Option 2")]
    public bool Option2 { get; set; }
}

Then you pass this model to the view you're showing (controller):

public ActionResult EditMyForm()
{
    var viewModel = new MyViewModel()
    return View(viewModel);
}

with the form:

@model MyViewModel
@using( Html.BeginForm())
{
    @Html.Label("Your choice")

    @Html.LabelFor(model => model.Option1) // here the 'LabelFor' will show you the name you set with DisplayName attribute
    @Html.CheckBoxFor(model => model.Option1)

    @Html.LabelFor(model => model.Option2)
    @Html.CheckBoxFor(model => model.Option2)
    <p>
        <input type="submit" value="Submit"/>
    </p>
}

Now here the HTML helpers (all the CheckBoxFor, LabelFor, EditorFor etc) allow to bind the data to the model properties.

Now mind you, an EditorFor when the property is of type bool will give you the check-box in the view, too. :)

And then, when you submit to the controller, it will auto-bind the values:

[HttpPost]
public ActionResult EditMyForm(MyViewModel viewModel)
{
    //And here the view model's items will be set to true/false, depending what you checked.
}
like image 187
Patryk Ćwiek Avatar answered Oct 01 '22 23:10

Patryk Ćwiek