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!