ASP.Net MVC: Multiple Checkboxes and Strongly Typed Views

This might be a first, but I actually stole this from myself off Stackoverflow. Posted it and thought it might be useful to share with the 1 live person who reads this blog and the 90 other bots… And I’m not sure about the 1 live person.

So here’s the situation, it’s late, you’ve got a strongly typed view that has a checkbox list, and you are desperate for an answer on how to handle it…. and now you’re scraping the bottom of the barrel. Well, good news is, I have the answer.

Let’s say you have a Book class that has a list of Categories. The Category class is simple, just has an id and name.

  public class Book
  {
    public Int32 BookId { get; set; }
    public IList<Category> Categories { get; set; }
  }

  public class Category
  {
    public Int32 Id { get; set; }
    public String Name { get; set; }
  }

Now you could try and figure out a way to create a typed view using the Book class. You could also stomp on your left foot until it bleeds. Who am I to judge you for liking pain? (Sick f—) For those who don’t want to go through that nightmare, I have an alternative: Create two new classes, one to set the view and one to handle the post back.

public class ViewBookModel
{
  public ViewBookModel(Book book, IList<Categories> categoryList)
  {
    BookId = book.Id;
    CategoryList = categoryList;
  }

  public Int32 BookId { get; private set; }
  IList<Categories> CategoryList { get; set; }
}

First the class to set the view. As you can see, there is a book id that corresponds to a book object’s id (DUH) and the category list which you will set in the original action.

  [AcceptVerbs(HttpVerbs.Get)]
  public ActionResult EditBook(Int32 bookId)
  {
     Book foundBook = Book.GetById(bookId);
     IList<Category> categoryList = Category.GetAll();
     ViewBookModel model = new ViewBookModel(foundBook, categoryList);
     return View(model);
  }

And then your markup for the checkbox list will be something like this:

  <%
    foreach(var category in Model.CategoryList)
    {
  %>
      <input type="checkbox" name="CategoryIds" value="<%= category.Id %>" />
  <%
    }
  %>

Notice that the name for every input is CategoryIds. This is because this will be the name of the collection of ids on the model for posting:

  public class ViewBookInModel
  {
    public String BookId { get; set; }
    public Int32[] CategoryIds { get; set; }
  }

And the action method would look like:

  [AcceptVerbs(HttpVerbs.Post)]
  public ActionResult UpdateBook(ViewBookInModel book)
  {
    foreach(Int32 id in book.CategoryIds)
    {
      ...
    }
  }

And boom, problem solved. You can now use a strongly typed View with a checkbox list. Go forth and be fruitful.

  • http://thedailyreviewer.com/top/ The Daily Reviewer

    Hi!

    Congratulations! Your readers have submitted and voted for your blog at The Daily Reviewer. We compiled an exclusive list of the Top 100 Programming Blogs, and we are glad to let you know that your blog was included! You can see it at http://thedailyreviewer.com/top/programming/2

    You can claim your Top 100 Blogs Award here : http://thedailyreviewer.com/pages/badges/programming

    P.S. This is a one-time notice to let you know your blog was included in one of our Top 100 Blog categories. You might get notices if you are listed in two or more categories.

    P.P.S. If for some reason you want your blog removed from our list, just send an email to angelina@thedailyreviewer.com with the subject line “REMOVE” and the link to your blog in the body of the message.

    Cheers!

    Angelina Mizaki
    Selection Committee President
    The Daily Reviewer
    http://thedailyreviewer.com

  • sha

    Can you post the sourc code please

  • sha

    Can you post the source code please

  • Brian

    This works great until you introduce validation.

  • George

    Does this preserve value of checkbox after postback ? In my case it works fine but it dont keep checkboxes checked after postback.

    Thanks!

    • http://www.byatool.com Sean

      You’ll have to set them using your model. If you are new to MVC (And sorry if you aren’t I might just be misunderstanding what you’re asking), you might be used to viewstate holding values. In MVC, you are responsible for setting the values of the check boxes yourself using your model or other, personally speaking, less elegant ways. You will lose all values on the page if you don’t.