In this recipe, we will display a view with a list of checkboxes. We will then look at how to catch that collection when it is posted back to the handling controller.
We will be using our Product
and ProductRepository
classes from the previous recipe. This means that we will also be using the NBuilder tool to generate a list of product data for us.
Product
and ProductRepository
class (copied over from the first recipe).Controllers/HomeController.cs:
public ActionResult Index() { ViewData["Products"] = new ProductRepository().GetProducts(); return View(); }
ProductId
integer, which is important for the next step.Views/Home/Index.aspx:
<% using (Html.BeginForm()) { %> <% List<Product> products = ViewData["Products"] as List<Product>;%> <% foreach (Product p in products) { %> <div><input type="checkbox" name="products" value="<%= p.ProductId %>" /> <%= p.Name %></div> <% } %> <input type="submit" value="Submit" /> <% } %>
There are a couple ways to display checkboxes and radio buttons. Both are included in the code download. I will present the first method in this recipe and the second method in the next recipe.
ProductId
from the last step.Controllers/HomeController.cs:
[HttpPost] public ActionResult Index(Int32[] products) { //do some work with the selected products ViewData["Products"] = new ProductRepository().GetProducts(); return View(); }
In this recipe, we took a look at how to use a traditional HTML input checkbox. This included creating a form. We then iterated over our collection of products and output a checkbox in its place. In order to capture the selected checkboxes, we created a new post—the only action that expected an array of integers.
You may have noticed that a traditional HTML input field was used in this example. There is, of course, an Html.CheckBox
included in the MVC framework. An example of how this works is included in the code download. In the next recipe, we will see a version of this around the concept of radio buttons.