Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically set the disabled html attribute for TextBoxFor HtmlHelper

I'm trying to dynamically set the disabled attribute for the TextBoxFor HtmlHelper

@Html.TextBoxFor(model => model.Street, 
                 new
                 {
                    @class = "", 
                    disabled = (Model.StageID==(int)MyEnum.Sth) ? "disabled" : "" 
                 })

but even if there is disabled="" it is the same as disabled="disabled". How to get around of this ?

like image 324
Tony Avatar asked Apr 18 '12 10:04

Tony


People also ask

How disable HTML TextBoxFor in MVC?

You can make the input 'read only' by using 'readonly'. This will let the data be POSTED back, but the user cannot edit the information in the traditional fashion.

What is Html TextBoxFor?

TextBoxFor() The TextBoxFor<TModel, TProperty>() is the generic extension method that creates <input type="text"> control. The first type parameter is for the model class, and second type parameter is for the property.

What is the difference between HTML TextBox vs HTML TextBoxFor?

IMO the main difference is that Textbox is not strongly typed. TextboxFor take a lambda as a parameter that tell the helper the with element of the model to use in a typed view. You can do the same things with both, but you should use typed views and TextboxFor when possible.

How do you give ID in Razor syntax?

Just add the id property to the html-attributes. That will override the default id generated by the editorfor-helper-methode. Save this answer.


1 Answers

I have the same problem about month ago and I finished by using this extension method for it

public static class AttributesExtensions
{
    public static RouteValueDictionary DisabledIf(
        this object htmlAttributes, 
        bool disabled
    )
    {
        var attributes = new RouteValueDictionary(htmlAttributes);
        if (disabled)
        {
            attributes["disabled"] = "disabled";
        }
        return attributes;
    }
}

And after that you can use it like this

@Html.TextBoxFor(
    model => model.Street, 
    new { @class = "" }.DisabledIf(Model.StageID==(int)MyEnum.Sth)
)

EDIT (after Paul's comment):

The using of data-xxx html attributes may be mined by using the constructor of the System.Web.Routing.RouteValueDictionary class, since underscores will not be automatically converted to minus sign.

Use the method System.Web.Mvc.HtmlHelper.AnonymousObjectToHtmlAttributes instead: will solve this issue.

UPDATED CODE (Extension method body only)

var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
if (disabled)
{
    attributes["disabled"] = "disabled";
}
return attributes;
like image 139
Chuck Norris Avatar answered Sep 29 '22 01:09

Chuck Norris