0

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?

John M
  • 14,338
  • 29
  • 91
  • 143
  • This post was helpful: http://stackoverflow.com/questions/6849774/mvc3-creating-checkbox-for-nullable-boolean – John M Apr 09 '12 at 19:43

5 Answers5

2

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; }
   }
}
david.s
  • 11,283
  • 6
  • 50
  • 82
  • I just tried and got an error message: Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions. – John M Apr 09 '12 at 19:27
  • Thanks @david.s - I was wondering if the model could be updated. Do you know of a way to avoid having Entity Framework linking the ActiveBool field to the database? – John M Apr 09 '12 at 20:04
  • Use the `[NotMapped]` attribute. – david.s Apr 09 '12 at 20:07
1

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.

Andy
  • 8,432
  • 6
  • 38
  • 76
0

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

}
Eduardo Molteni
  • 38,786
  • 23
  • 141
  • 206
0

try this one

    @model bool

   <div class="editor-for">
       @Html.CheckBox("", Model, new{@class="tickbox-single-line"})
   <div>
Hadi R.
  • 403
  • 3
  • 12
0

Try this:

@Html.CheckBox("Model", "Model")