Is there any way to bind a checkbox list to a model in asp.net mvc
Asked Answered
T

3

12

I am looking here to find a quick and easy way to bind a list of checkbox list items when the postback occurs in the model.

Apparently the common way to do it now seems to do it like this form.GetValues("checkboxList")[0].Contains("true"); It seems painfull and not exactly safe.

Is there a way to bind a list of checkbox (that are created with or without an helper in the view) or even an array of data for that matters during the UpdateModel(myViewModel, form.ToValueProvider()); phase which would populate an IList<string> or string[] inside of the model ?

Toscano answered 3/2, 2011 at 16:15 Comment(0)
L
9

You could start with a model:

public class MyViewModel
{
    public int Id { get; set; }
    public bool IsChecked { get; set; }
}

then a controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new[] 
        {
            new MyViewModel { Id = 1, IsChecked = false },
            new MyViewModel { Id = 2, IsChecked = true },
            new MyViewModel { Id = 3, IsChecked = false },
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(IEnumerable<MyViewModel> model)
    {
        // TODO: Handle the user selection here
        ...
    }
}

a View (~/Views/Home/Index.aspx):

<% using (Html.BeginForm()) { %>
    <%=Html.EditorForModel() %>
    <input type="submit" value="OK" />
<% } %>

And finally a corresponding editor template:

<%@ Control 
    Language="C#"
    Inherits="System.Web.Mvc.ViewUserControl<AppName.Models.MyViewModel>" %>
<%= Html.HiddenFor(x => x.Id) %>
<%= Html.CheckBoxFor(x => x.IsChecked) %>

Now when you submit the form in the POST action you will get the list of selected values along with their id.

Loads answered 3/2, 2011 at 22:47 Comment(3)
Idea is not bad, but it does not work when you use a form with other items than this. Say for instance there is a username/password + a collection of checkbox, this way it can't work :/Toscano
@Erick, of course that it can work. Your view model will now contain simple properties such as Username and Password and a collection property IEnumerable<MyViewModel> which will contain the checkboxes information. Now instead of using Html.EditorForModel in your form you would have simple <%= Html.TextBoxFor(x => x.Username) %> and <%= Html.PasswordFor(x => x.Password) %> and a <%= Html.EditorFor(x => x.MyCheckboxes) %> which will render the same editor template.Loads
I read many ways of accomplishing this, and this was by far the most elegant solution. Thanks!Twana
C
9

Here's the quick and easy way. Just set the value attribute inside your checkbox input elements and give them all the same name. If I was implementing this in a site, I would create a CheckBox helper method that takes name, value and isChecked parameters, but here's the View with just the html needed:

<% using (Html.BeginForm()) { %>
  <p><input type="checkbox" name="checkboxList" value="Value A" /> Value A</p>
  <p><input type="checkbox" name="checkboxList" value="Value B" /> Value B</p>
  <p><input type="checkbox" name="checkboxList" value="Value C" /> Value C</p>
  <p><input type="checkbox" name="checkboxList" value="Value D" /> Value D</p>
  <p><input type="checkbox" name="checkboxList" value="Value E" /> Value E</p>
  <p><input type="checkbox" name="checkboxList" value="Value F" /> Value F</p>
  <input type="submit" value="OK" />
<% } %>

In your Controller:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(IEnumerable<string> checkboxList)
{
    if (checkboxList != null)
    {
        ViewData["Message"] = "You selected " + checkboxList.Aggregate("", (a, b) => a + " " + b);
    }
    else
    {
        ViewData["Message"] = "You didn't select anything.";
    }

    return View();
}

The IEnumerable<string> parameter (you could make it IList<string> if you want) will contain only the values of the checked items. It will be null if none of the boxes are checked.

Caines answered 25/3, 2011 at 20:22 Comment(3)
I think it is not a good idea to put native html code there because it will be a pain if the user wants to bind the model to checkboxesAudrieaudris
@tugberk, I said that I would use a helper method in production code. I was just trying to show the answer to the original question. I'll add the helper method code.Caines
This is the correct answer. If you try to use the built-in Html.CheckBox() helpers they insist on inserting hidden fields with value="false", and that interferes with model binding.Duhamel
S
0

This works pretty well using a custom model binder and regular HTML...

First, your HTML form in Razor syntax:

@using (Html.BeginForm("Action", "Controller", FormMethod.Post)) {
    <ol>
        <li><input type="textbox" name="tBox" value="example of another form element" /></li>

        <li><input type="checkbox" name="cBox" value="1" /> One</li>
        <li><input type="checkbox" name="cBox" value="2" /> Two</li>
        <li><input type="checkbox" name="cBox" value="3" /> Three</li>
        <li><input type="checkbox" name="cBox" value="4" /> Four</li>
        <li><input type="checkbox" name="cBox" value="5" /> Five</li>

        <li><input type="submit" /></li>
    </ol>
}

(FormMethod.Post could also be .Get, doesn't matter for this)

Then, in proper MVC sense have a model object which represents your form submission:

public class CheckboxListExampleModel {
    public string TextboxValue { get; set; }
    public List<int> CheckboxValues { get; set; }
}

And a custom model binder class (I like to put this inside the model being bound, so I'll repeat the model created above to show where I'd add it. Placing it inside also allows the binder to use private property setters, which is a Good Thing):

public class CheckboxListExampleModel {
    public string TextboxValue { get; private set; }
    public List<int> CheckboxValues { get; private set; }

    public class Binder : DefaultModelBinder {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
            var model = new CheckboxListExampleModel();

            model.TextboxValue = bindingContext.GetValueAsString("tBox");

            string checkboxCsv = bindingContext.GetValueAsString("cBox");
            // checkboxCsv will be a comma-separated list of the 'value' attributes
            //   of all the checkboxes with name "cBox" which were checked
            model.CheckboxValues = checkboxCsv.SplitCsv<int>();

            return model;
        }
    }
}

.GetValueAsString() is an extension method used for clarity, here it is:

    public static string GetValueAsString(this ModelBindingContext context, string formValueName, bool treatWhitespaceAsNull = true) {
        var providerResult = context.ValueProvider.GetValue(formValueName);
        if (providerResult.IsNotNull() && !providerResult.AttemptedValue.IsNull()) {
            if (treatWhitespaceAsNull && providerResult.AttemptedValue.IsNullOrWhiteSpace()) {
                return null;
            } else {
                return providerResult.AttemptedValue.Trim();
            }
        }
        return null;
    }

.SplitCsv<T>() is also an extension method, but it's a common enough need and messy enough code that I'll leave it as an exercise for the reader.

And finally, your action to handle the form submit:

[HttpPost]
public ActionResult Action([ModelBinder(typeof(CheckboxListExampleModel.Binder))] CheckboxListExampleModel model) {
    // stuff
}
Sonnnie answered 12/3, 2015 at 14:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.