开发者

Enabling & disabling a textbox in razor view (ASP.Net MVC 3)

I want to Enable or Disable a textbox based on the value (Model.CompanyNameEnabled).

The below code is not worki开发者_JAVA百科ng. Please rectify.

@{
    string displayMode = (Model.CompanyNameEnabled) ? "" : "disabled = disabled";
    @Html.TextBox("CompanyName", "", new { displayMode })
}


@{
   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


<input id="textbox1" type="text" @{@((Model.CompanyNameEnabled) ? null : new { disabled = "disabled" })}; />

Haven't tested it, but should work


A simple approach:

@Html.TextBoxFor(x => x.Phone, new { disabled = "disabled", @class = "form-control" })


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.

  1. Assign a class to the HTML inputs you want to be disabled / enabled (id will do for a single item just as fine of course). In the example below I assigned a class 'switch-disabled' to the input.
@Html.TextBox("CompanyName", "", new { htmlAttributes = new { @class = "form-control switch-disable" } })
  1. Use javascript(jquery) to enable / disable the disabled parameter in HTML. In my example below I do this at the page load.
<script>
$(document).ready(() => {
    if(@Model.CompanyNameEnabled)
    {
        $('.switch-disable').attr("disabled", false);
    }else{
        $('.switch-disable').attr("disabled", true);
    }
});
</script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜