Reputation: 6762
I am working on a page where i want to add class to a control based on a condition. I tried the below code but when I add dynamic class name in cshtml file it renders in a wrong way. Any suggestion?
object TitleClass = (Model.Id != 0 && Model.IsApproved) ?
(object)new { @disabled = "disabled", @class = "headerBox" } : new{ @class = "headerBox"};
<div>
@Html.TextBoxFor(model => model.Title, new { @placeholder = "New Title", TitleClass })
@Html.ValidationMessageFor(model => model.Title)
</div>
Rendered as
<input name="Title" id="Title" type="text" placeholder="New Demand Title" value="cpx appr with orders" data-val-required="Enter Demand Title" data-val="true" titleclass="{ disabled = disabled, class = headerBox }">
Trying to make it render as
<input name="Title" id="Title" type="text" placeholder="New Demand Title" value="cpx appr with orders" data-val-required="Enter Demand Title" data-val="true" disabled = disabled class = headerBox >
Upvotes: 0
Views: 312
Reputation:
You need to add the placeholder
attribute to TitleClass
to avoid creating 2 sets of new anonymous objects
object TitleClass = (Model.Id != 0 && Model.IsApproved) ?
(object)new { @placeholder = "New Title", @disabled = "disabled", @class = "headerBox" } : (object)new{ @placeholder = "New Title", @class = "headerBox"};
and change the TextBoxFor()
method to
@Html.TextBoxFor(m => m.Title, TitleClass)
Side note: setting disabled = "disabled"
means the value of the the textbox wont post back and property Title
will be null in the controller
Upvotes: 1
Reputation: 11721
Try:
object attributes = (Model.Id != 0 && Model.IsApproved) ?
(object)new { @placeholder = "New Title", @disabled = "disabled", @class = "headerBox" } : new{ @placeholder = "New Title", @class = "headerBox"};
<div>
@Html.TextBoxFor(model => model.Title, attributes)
@Html.ValidationMessageFor(model => model.Title)
</div>
Upvotes: 1