MVC3 Conditionally disable Html.TextBoxFor()

前端 未结 5 1020
再見小時候
再見小時候 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:17

    The solution posted by @epignosisx works, but it may be a problem if you want to add some other attribute because you will have to add it it both objects (the one with disabled and the one now its empty).

    Even worse if you have some other bool property because you will have four different objects, each one for each combination.

    The best solution here (with a little more code) is to build an extension method for HtmlHelper to receive your boolean property as a parameter.

    public static MvcHtmlString TextBoxDisabledFor(this HtmlHelper htmlHelper, Expression> expression, bool disabled, object htmlAttributes = null)
    {
        return TextBoxDisabledFor(htmlHelper, expression, disabled, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
    }
    
    public static MvcHtmlString TextBoxDisabledFor(this HtmlHelper htmlHelper, Expression> expression, bool disabled, IDictionary htmlAttributes)
    {
        if (htmlAttributes == null)
            htmlAttributes = new Dictionary();
        if (disabled)
            htmlAttributes["disabled"] = "disabled";
        return htmlHelper.TextBoxFor(expression, htmlAttributes);
    }
    

    Here there is another example

提交回复
热议问题