Friday, May 9, 2014

MVC4 Custom Checkbox Template

On this particular project, I have a class based on a sql table the contains two columns of (nullable) datatype bit. In the model class file, I declared the properties as:

   public Nullable<bool>WKCInd { get; set; }
   public Nullable<bool>ExcAllInd { get; set; }

In the view, binding to the model using EditorFor creates a drop-down list with three possible values - true, false, and not set (null). I wanted to use check boxes for these two fields, but a checkbox can only have one of two values: true or false. That's where EditorTemplates come in. You can create custom templates that will display your data the way you want.

So I added a folder called EditorTemplates under the /Views/Shared folder (path and folder names must follow this convention). Then I created my template. I called it YesNo.cshtml. You can call it whatever you want, but it should be descriptive. In it, I put the razor syntax that would render my 3-value field into a 2-value checkbox:

   @model bool? 
   @Html.Checkbox ( "Model.GetValueOrDefault() )

And on the view itself, I bound to the model with:

   @Html.EditorFor(model => model.WKCInd)
   @Html.EditorFor(model => model.ExcAllInd)

Finally, to tie it all together, I added [UIHint("YesNo")] above the declaration of each bool property in the class. One final note, because my template only allows yes and no values, I no longer have the possibility of someone entering a null/not set value for these fields. I was able to change the property declarations to:

   [UIHint("YesNo")]
   public bool WKCInd { get; set;]

   [UIHint("YesNo")]
   public bool ExcAllInd { get; set;}