10

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.

0

3 Answers 3

15

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)
Sign up to request clarification or add additional context in comments.

Comments

0

The best thing to do would be to create a template that can be reused. I have some code at home that I can post later tonight.

Maybe check SO for similar posts in the mean time.

Dynamic list of checkboxes and model binding

Comments

0

This blog post also could help;

http://tugberkugurlu.com/archive/how-to-handle-multiple-checkboxes-from-controller-in-asp-net-mvc-sample-app-with-new-stuff-after-mvc-3-tools-update

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.