…meie igapäevast IT’d anna meile igapäev…

2011-06-27

ASP.NET MVC: Simple checkbox extension

Filed under: ASP.NET MVC — Sander @ 13:41:00
Tags: ,

As you may or may not have noticed, ASP.NET MVC checkbox implementation is just bad. In addition of regular <input type="checkbox".. it will render secondary hidden input, ” so that an unselected check box will return false”. This is supposed “make it easy to bind to view data or model data”. Considering how forums are full of people asking why their checkboxes misbehave, I’d say it is fairly safe to claim they failed.

I got tired of writing <input type=”checkbox” name=”mycheckbox” id=”mycheckbox” /> every time I needed a “normal”, checkbox, so I wrote a set SimpleTextbox extensions for InputExtensions (Html.SimpleTextbox()):

public static class SimpleCheckboxHelper
{
  public static MvcHtmlString SimpleCheckbox(this HtmlHelper helper, string name)
  {
    return SimpleCheckbox(helper, name, false, null);
  }

  public static MvcHtmlString SimpleCheckbox(this HtmlHelper helper, string name, bool @checked)
  {
    return SimpleCheckbox(helper, name, @checked, null);
  }

  public static MvcHtmlString SimpleCheckbox(this HtmlHelper helper, string name, bool @checked, object htmlAttributes)
  {
    return SimpleCheckbox(helper, name, @checked, new RouteValueDictionary(htmlAttributes));
  }

  public static MvcHtmlString SimpleCheckbox(this HtmlHelper helper, string name, bool @checked, IDictionary<String, Object> htmlAttributes)
  {
    string attributes = string.Empty;
    if (htmlAttributes != null && htmlAttributes.Count > 0)
      attributes = htmlAttributes.Aggregate(attributes, (current, htmlAttribute) => current + string.Format(" {0}=\"{1}\"", htmlAttribute.Key, htmlAttribute.Value));

    var s = string.Format("<input type=\"checkbox\" name=\"{0}\" id=\"{0}\"{1}{2}/>", name, @checked ? " checked=\"checked\"" : string.Empty, attributes);
    return new MvcHtmlString(s);
  }
}

(code formatted with http://quickhighlighter.com/code-syntax-highlighter.php, as I cannot currently use my normal utilities)

Using SimpleCheckbox is same as using normal ASP.NET MVC checkbox:

  • @Html.SimpleCheckbox(“Active”) – renders normal checkbox, not checked.
  • @Html.SimpleCheckbox(“Active”, Model.Active) – checked if Model.Active is true, unchecked if not.
  • @Html.SimpleCheckbox(“Active”, Model.Active, new { @class = “mycheckboxclass” }) – adds CSS class (or other attributes) to the checkbox.

Blog at WordPress.com.