Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable input element using razor

I need to disable an input dynamically when its value is equal to "*". How can I achieve this using the MVC Razor?

    @Html.TextBoxFor(m => m.Digits[0], new { @class = "form-control input-lg label_16", @placeholder = 
"1st", (Model.Digits[0] == "*" ? "disabled" : "") })

The above code doesn't compile Is this possible?

like image 518
Bonomi Avatar asked Oct 03 '14 13:10

Bonomi


1 Answers

Try using ternary operator

@Html.TextBoxFor(m => m.Digits[0], Model.Digits[0] == "*" ? (object)new { @class = "form-control input-lg label_16", @placeholder = 
"1st", @disabled = "disabled" } : new { @class = "form-control input-lg label_16", @placeholder = 
"1st" })

in the code above, the second parameter of @Html.TextBoxFor helper method will be based on the value of Model.Digits[0]. If it's * then the parameter would include the disabled attribute

new { @class = "form-control input-lg label_16", @placeholder = 
"1st", @disabled = "disabled" }

otherwise

new { @class = "form-control input-lg label_16", @placeholder = 
"1st" }
like image 180
ekad Avatar answered Sep 19 '22 01:09

ekad