aspnet razor 编辑器用于有条件地添加属性

aspnet razor editorfor conditionally add attribute

我使用以下方法创建表单控件:

@Html.DropDownList("FK_CompID", null, htmlAttributes: new { @class = "form-control", @readonly = "readonly"})

但是当我需要有条件地设置它是否只读时,我将删除该属性,

有没有办法这样处理:

@Html.DropDownList("FK_CompID", null, htmlAttributes: new { @class = "form-control", @readonly = null})

并且不应添加到元素中?

您需要根据某些 属性 构建定义 html 属性的对象,然后在 DropDownList() 方法中使用它。假设你的模型包含一个 属性 bool IsReadOnly,那么

@{
    var attributes = Model.IsReadOnly ? 
    (object)new { @class = "form-control", readonly = "readonly" } :
    (object)new { @class = "form-control"};
}
@Html.DropDownList("FK_CompID", null, attributes)

我通过使用@Html.EditorFor() 和 htmlAttributes 实现了这个功能。

您可以设置HTML属性如下

@Html.EditorFor(modelItem => Model.item, new { name ="name", htmlAttributes = new { @readonly = "readonly" } })

这对我设置 sortable table 使编辑器字段只读有效。