14

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?

sharptooth
  • 167,383
  • 100
  • 513
  • 979

2 Answers2

11

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.
}
Patryk Ćwiek
  • 14,078
  • 3
  • 55
  • 76
  • Mentioning EditorFor is a good point. EditorFor is useful almost always. Depending the data type it creates text input, textarea, checkbox and so on. – ozgur Apr 01 '16 at 20:10
3

First you define SelectList for Options. This will be used just to render checkboxes

    public IList<SelectListItem> OptionsSelectList { get; set; }

Than, you define model that will hold value of single chosen option after post

public class ChooseOptionViewModel
{
    public int OptionIdentifier { get; set; } //name or id
    public bool HasBeenChosen { get; set; } //this is mapped to checkbox
}

Then IList of those options in ModelData

public IList<ChooseOptionViewModel> Options { get; set; }

And finally, the view

    @for (int i = 0; i < Model.OptionsSelectList.Count(); i++)
    {
        <tr>
            <td class="hidden">
                @Html.Hidden("Options[" + i + "].OptionIdentifier", Model.OptionsSelectList[i].Value)
            </td>
            <td>
                @Model.OptionsSelectList[i].Text
            </td>
            <td>
                @Html.CheckBox("Options[" + i + "].HasBeenChosen", Model.Options != null && Model.Options.Any(x => x.OptionIdentifier.ToString().Equals(Model.OptionsSelectList[i].Value) && x.HasBeenChosen))
            </td>
        </tr>
    }

After post, you just inspect Options.Where(x => x.HasBeenChosen)

This is full-functional, and it will allow you to redisplay view when validation errors occur, etc. This seems a bit complicated, but I haven't come up with any better solution than this.

archil
  • 39,013
  • 7
  • 65
  • 82