7
我建立一个形式的htmlAttributes和我有使用条件的内联添加readonly
HTML属性保持:如何避免重复内嵌条件语句来定义Html.EditorFor()
@Html.LabelFor(model => model.EventDate)
<div class="row">
<div class="col-xs-3">
@Html.EditorFor(model => model.EventDate, new
{
htmlAttributes = Model.IsEditorReadOnly ?
(object)new { @class = "form-control input-lg", @type = "date", @readonly = "readonly" } :
(object)new { @class = "form-control input-lg", @type = "date" }
})
</div>
</div>
@Html.ValidationMessageFor(model => model.EventDate)
你可以用”对于@readonly
属性的值使用条件,因为即使它设置为null,它也会以readonly=""
的形式呈现给客户端,并且这足以让浏览器将该字段设置为只读。
为了添加单个属性,必须有一个更好的方法来做到这一点,而不是每个表单元素的内联条件?
你可以创建你自己的HtmlHelper扩展方法 - 说'@ Html.ReadOnlyEditorFor(表达,htmlAttributes,isReadonly =真)'其中属性取决于的增值'isReadonly'参数 –
@StephenMuecke如何修改该助手内的htmlAttributes对象以添加/删除'@ readonly'属性? – travis
参考[这个答案](http://stackoverflow.com/questions/30127866/create-checkboxfor-mvc-helper-with-title-attribute-from-model-description/30135407#30135407)为例 –