2015-11-04 66 views
-1

我用下面的方法来创建表单控件:ASPNET剃刀editorfor有条件地添加属性

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

但是当我需要使它有条件无论是只读还是不肯,我就删除属性,

有什么办法来处理这样的:

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

,应不会添加到元素?

+0

你需要向我们展示什么是确定条件的属性 –

回答

0

您需要根据某些属性构建定义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) 
+0

用'@ Html.EditorFor()'尝试这个,它只是简单的不想工作。 :( –

+0

@ ScottK.Fraley,问一个新问题(和'EditorFor()'没有接受HTML属性的重载,除非你使用MVC-5.1或更高版本,然后它的语法不同。 –

+0

实际上,我切换到'@ Html.TextBoxFor(m => m.TaxPayer,attributes)',它工作的很好!现在,如果我可以让'@ Html.TextBoxFor()'渲染我的dang提示/占位符,如'DisplayAttribute'我将全部设置! –

0

我通过@ Html.EditorFor()和htmlAttributes得到了这个工作。

您可以设置HTML属性如下

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

这个工作对我设置的可分类表有编辑的字段只读。