Caverman
Caverman

Reputation: 3707

MVC 5 TextBoxFor not able to do conditional Bootstrap CSS?

I'm using a TextBoxFor and what I need to do is see if a property is NULL or Blank. If so then I need to let the end user type in their info. If not, meaning I can find their name, I need to disable the field so that they can not alter it.

I did some searching and try these two options but they are not working.

@Html.TextBoxFor(m => m.EmployeeName, string.IsNullOrWhiteSpace(Model.EmployeeName) ? new { Class = "form-control" } : new { Class = "form-control", disabled = "disabled" })

@Html.TextBoxFor(m => m.EmployeeName, new { Class = "form-control", string.IsNullOrWhiteSpace(Model.EmployeeName) ? disabled = "disabled" : null })

Any ideas on what I can try?

Upvotes: 1

Views: 319

Answers (1)

user3559349
user3559349

Reputation:

Your current code would be giving an error because there is no implicit conversion between the 2 anonymous types and you would need to cast them to object

var attributes = String.IsNullOrWhiteSpace(Model.EmployeeName) ? 
    (object)new { @class = "form-control" } : 
    (object)new { @class = "form-control", disabled = "disabled" })

@Html.TextBoxFor(m => m.EmployeeName, attributes)

Note however that disabling an control means its value will not be submitted, so if EmployeeName initially has a value, it will be null when submitted. You might want to consider using readonly = "readonly" instead.

Upvotes: 1

Related Questions