Display a byte as a checkbox using a EditorTemplate?

白昼怎懂夜的黑 提交于 2020-01-11 13:20:13

问题


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?


回答1:


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



回答2:


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.




回答3:


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

}



回答4:


try this one

    @model bool

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



回答5:


Try this:

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


来源:https://stackoverflow.com/questions/10078150/display-a-byte-as-a-checkbox-using-a-editortemplate

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