asp.net-mvcasp.net-mvc-3razorhtml-helper

Set disable attribute based on a condition for Html.TextBoxFor


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 = "width: 70px;", maxlength = "10", id = "expire-date" disabled = (Model.ExpireDate == null ? "disable" : "") })

This helper has two output disabled="disabled " or disabled="". both of theme make the textbox disable.

I want to disable the textbox if Model.ExpireDate == null else I want to enable it


Solution

  • 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<TModel, TProperty>(
            this HtmlHelper<TModel> htmlHelper, 
            Expression<Func<TModel, TProperty>> 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<TModel, TProperty>(
            this HtmlHelper<TModel> htmlHelper,
            Expression<Func<TModel, TProperty>> 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" 
        }
    )