Using @Html.CheckBox() with a dynamic value

by Oliver 19. November 2012 21:09

I’ve just spent much more time than I’d want on figuring out why the following code wouldn’t give me a checked checkbox, even when I set the ViewModel.Value to true:

public class ViewModel {
    public string  Name  { get; set; }
    public dynamic Value { get; set; }
}
@Html.CheckBox(Model.Name, (bool?)Model.Value)

The problem is with the signature of CheckBox, of course! Instead of calling the one where the second argument is of type bool, it calls the one where the second arg is of type object!

// the method I thought I was calling
public static MvcHtmlString CheckBox(this HtmlHelper htmlHelper, string name, bool isChecked) { 
    return CheckBox(htmlHelper, name, isChecked, (object)null /* htmlAttributes */);
}
 
// the method I in fact was calling
public static MvcHtmlString CheckBox(this HtmlHelper htmlHelper, string name, object htmlAttributes) {
    return CheckBox(htmlHelper, name, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)); 
}
 
// the method that's being called by the second method above: isChecked == null!
public static MvcHtmlString CheckBox(this HtmlHelper htmlHelper, string name, IDictionary<string, object> htmlAttributes) {
    return CheckBoxHelper(htmlHelper, null, name, null /* isChecked */, htmlAttributes); 
}

Even though they were not strictly necessary, still, the framework sources helped me out this time to find this subtle bug (in my code, of course!).

The solution to the problem looks like this:

@Html.CheckBox(Model.Name, (bool)(Model.Value == true))

Happy Coding!

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

About Oliver

shades-of-orange.com code blog logo I build web applications using ASP.NET and have a passion for javascript. Enjoy MVC and Orchard CMS, and I do TDD whenever I can. I like clean code. Love to spend time with my wife and our three children. My profile on Stack Exchange, a network of free, community-driven Q&A sites

About Anton

shades-of-orange.com code blog logo I'm a software developer at teamaton. I code in C# and work with MVC, Orchard, SpecFlow, Coypu and NHibernate. I enjoy beach volleyball, board games and Coke.