Search code examples
c#asp.net-mvc-3mvc-editor-templateseditortemplates

Display a byte as a checkbox using a EditorTemplate?


My model class:

public class StatusList
{
   public int StatusID {get;set;}
   [UIHint("ByteCheckbox")]
   public byte Active {get;set;}
}

In /Views/Shared/EditorTemplates I created a file called ByteCheckbox.cshtml

The editortemplate ByteCheckbox contains (My 3rd attempt):

@model byte
@if (Model == 1)
{
    @Html.CheckBox("", true)
}
else
{
    @Html.CheckBox("", false) 
}

Doing this nicely renders a checkbox. When I change the checkbox status and try to save the changes the model validation complains that the value is 'false' (or 'true') instead of the expected 0 or 1.

How to modify the editortemplate to allow for the value to be translated?


Solution

  • Have you tried this?

    <div class="editor-label">
        @Html.LabelFor(model => model.Active)
    </div>
    <div class="editor-field">
        @Html.CheckBoxFor(model => model.Active != 0)
        @Html.ValidationMessageFor(model => model.Active)
    </div>
    

    You can do this in your model:

    public class StatusList
    {
       public int StatusID {get;set;}
       public byte Active {get;set;}
       [NotMapped]
       public bool ActiveBool
       {
           get { return Active > 0; }
           set { Active = value ? 1 : 0; }
       }
    }