2015-11-04 57 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" } }) 

這個工作對我設置的可分類表有編輯的字段只讀。