1

I'm trying to add a disable attribute to the html that is generated via @html helper functions but can't seem to get something working that works in the attrib parameters of the html helper. what i have below will still write disabled for the html... but i can't remove it cause then the helper doesn't work.

i have a variable defined:

@{ var displayItem = (Model.TypeId == 100) }

@Html.TextBox("listitem", "", new {@class = "form-control", @disabled = (@displayItem ? "" : "disabled")})

but because i have to list the parameter @disabled, that produces html like this:

<input class="form-control"  disabled="" id="listitem" name="listitem"  type="text" value="" />

because disabled is listed it disables the input. but the html helper doesn't work unless i give it a parameter name.

How to write the disabled in the parameter list so that disabled doesn't show at all if it's not supposed to be disabled?

2 Answers 2

3

You can use

@{ var displayItem = (Model.TypeId == 100) }
@Html.TextBox("listitem", "", displayItem ? (object)new { @class = "form-control", disabled = "disabled" } : (object)new { @class = "form-control"});

or

@{
    var attributes = Model.TypeId == 100 ? (object)new { @class = "form-control", disabled = "disabled" } : (object)new { @class = "form-control"});
}
@Html.TextBox("listitem", "", attributes)

or a simple if block

@(if Model.TypeId == 100)
{
    @Html.TextBox("listitem", "", new {@class = "form-control", disabled = "disabled" })
}
else
{
    @Html.TextBox("listitem", "", new {@class = "form-control" })
}

Note that the value of disabled controls are not submitted, so a readonly attribute may be more appropriate

Sign up to request clarification or add additional context in comments.

1 Comment

ok, i was wondering if there was some other trick to doing the construction of the attribute parameter, but i guess not. Tx.
3

You also can use a Dictionary<string, object> and pass that to the html helper:

@{
    var attributes = new Dictionary<string, object>
    {
        { "class", "form-control" }
    };

    if (Model.TypeId == 100)
    {
        attributes.Add("disabled", "disabled");
    }
}

@Html.TextBox("listitem", "", attributes)

1 Comment

This is the most correct way in my opinion. The htmlAttributes parameter for HtmlHelpers can be either object or IDictionary<string, object>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.