Home > Net >  How to add disabled to html helper based on condition?
How to add disabled to html helper based on condition?

Time:04-28

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.

CodePudding user response:

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)

CodePudding user response:

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)
  • Related