Question

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?

Was it helpful?

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; }
   }
}

OTHER TIPS

Don't use Html.CheckBox; instead use Html.EditorFor. You'll need to define a file called ByteCheckbox.cshtml in Views/Shared/EditorTemplates for this to work as well.

You can also use a custom model binder.

Here's a sample for a decimal, but you can do it for the byte type.

public class DecimalModelBinder : DefaultModelBinder {

    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
        dynamic valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (valueProviderResult == null) {
            return base.BindModel(controllerContext, bindingContext);
        }

        return ((string)valueProviderResult.AttemptedValue).TryCDec();
    }

}

try this one

    @model bool

   <div class="editor-for">
       @Html.CheckBox("", Model, new{@class="tickbox-single-line"})
   <div>

Try this:

@Html.CheckBox("Model", "Model")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top