skip to Main Content

I’m trying to prevent user from using input in some condition but for disabling it if I add disabled to it, it will disable no matter that its value is true or false.

This is my code:

@Html.TextBoxFor(model => model.inputName, new { @disabled = (condition ? "true" : "false") })

In any condition it will be disabled.

2

Answers


  1. Because whether to disabled depend on your disabled attribute instead of the disabled attribute value

    Here is an example

    <p>Last name: <input type="text" name="lname" disabled="" /></p>
    <p>Last name: <input type="text" name="lname" disabled="true" /></p>
    <p>Last name: <input type="text" name="lname" disabled="false" /></p>

    if you don’t want to use Js to control your attribute we can judge that by if condition true to create the element with disabled otherwise not.

    @if(condition) 
    {
        Html.TextBoxFor(model => model.inputName, new { @disabled = "true" })
    }
    else
    {
        Html.TextBoxFor(model => model.inputName)
    }
    

    otherwise we can create an extension method for that.

    public static class TextBoxForExtensions
    {
        public static IHtmlString TextBoxFor<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);
        }
    }
    

    Then we can use like

    @Html.TextBoxFor(model => model.inputName, new{},condition)
    
    Login or Signup to reply.
  2. As I said in comment to this question you can add variable:

    var myAttributes = condition ? new {@disabled = true, /* add some more here*/} : new {/*add more here*/}
    

    Then you can add it in your helper:

    @Html.TextBoxFor(model => model.inputName, myAttributes)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search