Set disable attribute based on a condition for Html.TextBoxFor

后端 未结 12 1193
清酒与你
清酒与你 2020-11-28 06:13

I want to set disable attribute based on a condition for Html.TextBoxFor in asp.net MVC like below

@Html.TextBoxFor(model => model.ExpireDate, new { style         


        
12条回答
  •  醉酒成梦
    2020-11-28 06:30

    The valid way is:

    disabled="disabled"
    

    Browsers also might accept disabled="" but I would recommend you the first approach.

    Now this being said I would recommend you writing a custom HTML helper in order to encapsulate this disabling functionality into a reusable piece of code:

    using System;
    using System.Linq.Expressions;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Mvc.Html;
    using System.Web.Routing;
    
    public static class HtmlExtensions
    {
        public static IHtmlString MyTextBoxFor(
            this HtmlHelper htmlHelper, 
            Expression> expression, 
            object htmlAttributes, 
            bool disabled
        )
        {
            var attributes = new RouteValueDictionary(htmlAttributes);
            if (disabled)
            {
                attributes["disabled"] = "disabled";
            }
            return htmlHelper.TextBoxFor(expression, attributes);
        }
    }
    

    which you could use like this:

    @Html.MyTextBoxFor(
        model => model.ExpireDate, 
        new { 
            style = "width: 70px;", 
            maxlength = "10", 
            id = "expire-date" 
        }, 
        Model.ExpireDate == null
    )
    

    and you could bring even more intelligence into this helper:

    public static class HtmlExtensions
    {
        public static IHtmlString MyTextBoxFor(
            this HtmlHelper htmlHelper,
            Expression> expression,
            object htmlAttributes
        )
        {
            var attributes = new RouteValueDictionary(htmlAttributes);
            var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
            if (metaData.Model == null)
            {
                attributes["disabled"] = "disabled";
            }
            return htmlHelper.TextBoxFor(expression, attributes);
        }
    }
    

    so that now you no longer need to specify the disabled condition:

    @Html.MyTextBoxFor(
        model => model.ExpireDate, 
        new { 
            style = "width: 70px;", 
            maxlength = "10", 
            id = "expire-date" 
        }
    )
    

提交回复
热议问题