MVC3 Conditionally disable Html.TextBoxFor()

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

    I had this same problem and decided to write my own HtmlHelper extension method.

    public static MvcHtmlString Disable(this MvcHtmlString helper, bool disabled)
        {
            if (helper == null)
                throw new ArgumentNullException();
    
            if (disabled)
            {
                string html = helper.ToString();
                int startIndex = html.IndexOf('>');
    
                html = html.Insert(startIndex, " disabled=\"disabled\"");
                return MvcHtmlString.Create(html);
            }
    
            return helper;
        }
    

    This will accept a boolean to indicate if the control should be disabled or not. It just appends disabled="disabled" just inside the first > it comes across in a string.

    You can use it like below.

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

提交回复
热议问题