Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 936
Erick Avatar asked Feb 03 '11 16:02

Erick


People also ask

How can get CheckBox value in ASP.NET MVC?

Just add value="true" to the input tag. And use a hidden with value="false" as shown below.


2 Answers

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.

like image 97
Darin Dimitrov Avatar answered Sep 22 '22 18:09

Darin Dimitrov


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.

like image 39
CoderDennis Avatar answered Sep 18 '22 18:09

CoderDennis