Conditional html attribute with Html Helper

。_饼干妹妹 提交于 2019-11-27 09:47:06

While you could use

@Html.CheckBoxFor(m => m.Property, Model.IsAuthorized ? (object)new { @class = "input-class", disabled = "disabled" } : (object)new { @class = "input-class"});

to do this in one line of code, in your case it may result in model binding failing.

The CheckBoxFor() method generates 2 inputs, a checkbox with value="True" and a hidden input with value="False". In the case where the initial value of Property is true and IsAuthorized is true the result is that the checkbox is disabled and will not post a value. However the hidden input will be submitted and bind to your model, resulting in Property being false (when it should be true)

In order to handle model binding correctly, you will need the if block

@if (Model.IsAuthorized)
{
    @Html.CheckBoxFor(x => m.Property, new { @class = "input-class" })
}
else
{
    @Html.HiddenFor(m => m.Property) // necessary to post back the initial value
    <input type="checkbox" @(Model.Property ? "checked" : null) disabled />
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!