Display a byte as a checkbox using a EditorTemplate?

醉酒当歌 提交于 2019-12-02 12:35:37

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

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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!