MVC3 Conditionally disable Html.TextBoxFor()

前端 未结 5 1028
再見小時候
再見小時候 2020-12-06 09:24

I have a C# .Net web app. In that app I need to conditionally disable Html.TextBoxFor controls (also Html.DropDownListFor controls) based on who is

5条回答
  •  北荒
    北荒 (楼主)
    2020-12-06 10:22

    Extending @James's answer, I wrote this HtmlHelper extension that updates/removes the disabled attribute if it's already present, or adds it if not:

    public static MvcHtmlString Disable(this MvcHtmlString helper, bool disabled) {
        string html = helper.ToString();
        var regex = new Regex("(disabled(?:=\".*\")?)");
        if (regex.IsMatch(html)) {
            html = regex.Replace(html, disabled ? "disabled=\"disabled\"" : "", 1);
        } else {
            regex = new Regex(@"(\/?>)");
            html = regex.Replace(html, disabled ? "disabled=\"disabled\"$1" : "$1", 1);
        }
        return MvcHtmlString.Create(html);
    }
    

    It also plays nicely with self-closing tags (like ).

    Usage is the same:

    @Html.TextBoxFor(model => model.PropertyName).Disable(true)
    

    Tested on both @Html.DropDownListFor() and @Html.TextBoxFor().

提交回复
热议问题