1

I am lost with the submission of listbox with multiple itmes selected and with group of checkboxes.

If that was a WebForm project it wouldn't be a problem for me.

What are the best practices and maybe some code samples that show proper submission of form in ASP.NET MVC2 that contains group of checkboxes and listbox with mutiple selected items?

Here is the sample of the form:

Categories: - group of checkboxes

Topics: - listbox with multiple attribute (multiple="multiple")

1 Answer 1

1

As always start by defining the view model:

public class MyModel
{
    public bool Check1 { get; set; }
    public bool Check2 { get; set; }

    public IEnumerable<SelectListItem> ListItems { get; set; }
    public string[] SelectedItems { get; set; }
}

Next the controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new MyModel
        {   
            Check1 = false,
            Check2 = true,
            ListItems = new SelectList(new[]
            {
                new { Id = 1, Name = "item 1" },
                new { Id = 2, Name = "item 2" },
                new { Id = 3, Name = "item 3" },
            }, "Id", "Name")
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyModel model)
    {
        // TODO: Process the model
        // model.SelectedItems will contain a list of ids of the selected items
        return RedirectToAction("index");
    }
}

and finally the View:

<% using (Html.BeginForm()) { %>

    <div>
        <%: Html.LabelFor(x => x.Check1) %>
        <%: Html.CheckBoxFor(x => x.Check1) %>
    </div>

    <div>
        <%: Html.LabelFor(x => x.Check2) %>
        <%: Html.CheckBoxFor(x => x.Check2) %>
    </div>

    <div>
        <%: Html.ListBoxFor(x => x.SelectedItems, Model.ListItems) %>
    </div>

    <input type="submit" value="OK" />

<% } %>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Darin, Is it possible to use dynamic list of checkboxes as those values will come from DB? Cheers
Sure, use IEnumerable<bool>.

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.