Validating Checkboxes in ASP.NET MVC

So here’s a very barebones example that does validation to all the checkboxes on a page. Also, it does the following:

  • Maps the checkboxes to a dictionary object.
  • Creates a custom model binder (that maps the checkbox values to the dictionary object).

Let’s get started.

The Model

public class Event
{
  public string Name { get; set; }
  public Dictionary Weekdays { get; set; }
}

The Custom Model Binder

  public class EventBinder : IModelBinder
  {
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
      Event ev = new Event();      
 
      ev.Name = controllerContext.HttpContext.Request.Form["Name"];
 
      // Let's initialize all the keys to false
      ev.Weekdays = new Dictionary()
      {
        {"Monday", false },
        {"Tuesday", false },
        {"Wednesday", false },
        {"Thursday", false },
        {"Friday", false },
      };      
 
      // Now let's trigger to true when the checkbox is checked.
      if (controllerContext.HttpContext.Request.Form["Weekdays[Monday]"] == "on")
        ev.Weekdays["Monday"] = true;
 
      if (controllerContext.HttpContext.Request.Form["Weekdays[Tuesday]"] == "on")
        ev.Weekdays["Tuesday"] = true;
 
      if (controllerContext.HttpContext.Request.Form["Weekdays[Wednesday]"] == "on")
        ev.Weekdays["Wednesday"] = true;
 
      if (controllerContext.HttpContext.Request.Form["Weekdays[Thursday]"] == "on")
        ev.Weekdays["Thursday"] = true;
 
      if (controllerContext.HttpContext.Request.Form["Weekdays[Friday]"] == "on")
        ev.Weekdays["Friday"] = true;
 
      return ev;
    }
  }

The Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication6.Models;
 
namespace MvcApplication6.Controllers
{
  public class HomeController : Controller
  {
    public ActionResult Index()
    {
      // We need to instantiate an event object before setting the checkboxes to default.
      Event e = new Event();      
 
      // Let's initialize the checkboxes.
      e.Weekdays = new Dictionary()
      {
        {"Monday",    false },
        {"Tuesday",   false },
        {"Wednesday", false },
        {"Thursday",  false },
        {"Friday",    false },
      };
 
      ViewBag.IsFormValid = false;
 
      return View("Home", e);
    }
 
    [HttpPost]
    public ActionResult Index([ModelBinder(typeof(EventBinder))] Event e)
    {
      // Let's validate the name.
      if (e.Name.Length == 0)
      {
        ModelState.AddModelError("Name", "First name is required.");
      }
 
      // Validate the checkbox. Make sure they are all checked.
      foreach (var day in e.Weekdays)
      {
        if (day.Value == false)
        {
          ModelState.AddModelError("Weekdays[" + day.Key + "]", day.Key + " has to be checked!" );
        }
      }
 
      ViewBag.IsFormValid = false;
 
      if (ModelState.IsValid)
      {
        ViewBag.IsFormValid = true;
      }        
 
      return View("Home", e);
    }
  }
}

The View

@model MvcApplication6.Models.Event
@{
  Layout = null;
}
 
<!--
    .formErrors
    {
      color: Red;
    }
 
-->
<div>
<h1>Form Is: &lt;&lt; @ViewBag.IsFormValid &gt;&gt;</h1>
<h4>Fill out the name and check every checkbox so the form becomes true (valid).</h4>
@using (@Html.BeginForm("Index", "Home"))
    {
      // FirstName TextBox
      @Html.LabelFor(model =&gt; model.Name, "FirstName")
      @Html.TextBoxFor(model =&gt; model.Name, "FirstName")
      @Html.ValidationMessageFor(model =&gt; model.Name, null, new { @class = "formErrors" })   
<hr />
 
      // Weekday Checkboxes
      foreach (var day in Model.Weekdays)
      {
<input name="Weekdays[@day.Key]" type="checkbox" /> checked="checked" 
        }
        /&gt; @day.Key
 
        @Html.ValidationMessageFor(model =&gt; model.Weekdays[day.Key], null, new {@class="formErrors"})
 
      }      
<input type="submit" value="submit me" />
    }</div>

Leave a Reply