I'm using the following approach to create form controls:
@Html.DropDownList("FK_CompID", null, htmlAttributes: new { @class = "form-control", @readonly = "readonly"})
but when I need to make it conditionally whether it be read only or not I shall remove that attribute,
Is there any way to handle it like this:
@Html.DropDownList("FK_CompID", null, htmlAttributes: new { @class = "form-control", @readonly = null})
and should be not added to element?
You need to build an object defining the html attributes based on some property and then use that in the DropDownList()
method. Assuming you model contains a property bool IsReadOnly
, then
@{
var attributes = Model.IsReadOnly ?
(object)new { @class = "form-control", readonly = "readonly" } :
(object)new { @class = "form-control"};
}
@Html.DropDownList("FK_CompID", null, attributes)