Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Multiple Checkboxes

Tags:

c#

asp.net-mvc

I have a List of about 20 items I want to display to the user with a checkbox beside each one (a Available property on my ViewModel).

When the form is submitted, I want to be able to pass the value of each checkbox that is checked back to my controller method via the Selections property on my ViewModel.

How would I go about doing this using the Form Helper class in MVC? Is this even possible?

PS: I don't want a listbox where the user can just highlight multiple items.

like image 629
AndrewC Avatar asked Mar 10 '11 02:03

AndrewC


1 Answers

Model:

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

Controller:

public class HomeController: Controller
{

    public ActionResult Index()
    {
        var model = Enumerable.Range(1, 20).Select(x => new MyViewModel
        {
            Id = x
        });
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(IEnumerable<MyViewModel> model)
    {
        ...
    }
}

View ~/Views/Home/Index.cshtml:

@model IEnumerable<AppName.Models.MyViewModel>
@using (Html.BeginForm())
{
    @Html.EditorForModel()
    <input type="submit" value="OK" />
}

Editor template ~/Views/Home/EditorTemplates/MyViewModel.cshtml:

@model AppName.Models.MyViewModel
@Html.HiddenFor(x => x.Id)
@Html.CheckBoxFor(x => x.Available)
like image 152
Darin Dimitrov Avatar answered Oct 06 '22 09:10

Darin Dimitrov