I want to Enable or Disable a textbox based on the value (Model.CompanyNameEnabled
).
The below code is not working. Please rectify.
@{
@{
object displayMode = (Model.CompanyNameEnabled) ? null : new {disabled = "disabled" };
@Html.TextBox("CompanyName", "", displayMode)
}
You should pass htmlAttribute as anonymous object, with property names = html attribute names, property values = attribute values. Your mistake was that you were passing string instead of name=value pair
A simple approach:
@Html.TextBoxFor(x => x.Phone, new { disabled = "disabled", @class = "form-control" })
<input id="textbox1" type="text" @{@((Model.CompanyNameEnabled) ? null : new { disabled = "disabled" })}; />
Haven't tested it, but should work
As is already mentioned in this thread the suggested answer doesn't work in MVC5 anymore. There's actually an easy two step solution to that problem.
@Html.TextBox("CompanyName", "", new { htmlAttributes = new { @class = "form-control switch-disable" } })
<script>
$(document).ready(() => {
if(@Model.CompanyNameEnabled)
{
$('.switch-disable').attr("disabled", false);
}else{
$('.switch-disable').attr("disabled", true);
}
});
</script>