1

I was using a textbox to do the following:

<input style="width:50px;" type="text" id="blah" value="@model.value1" @if(model.id!=1){ <text>disabled</text>}/>

This basically shows a textbox which is disabled under specific circumstances. I decided to replace this with a more "mvc-friendly" way.

@Html.TextBoxFor(m => model.value1, new { id = "blah" })

But not sure how to add in the disabled attribute (Dynamically) I can get it to do it statically easilly by adding a disabled=truevalue into the new{}.

I did try using this: @if (<condition>) { var disable = true; } @Html.TextBoxFor(m => model.value1, new { id = "blah", disabled = disable })

But this also didn't work. Am i taking the right approach here?

2 Answers 2

3
@{
    var attributes = new Dictionary<string, object>
    {
        { "id", "blah" }
    };
    if (<condition>) 
    { 
        attributes["disabled"] = "disabled";
    }
}
@Html.TextBoxFor(m => model.value1, attributes)

Obviously that's ugly as hell and you should never even be thinking of polluting your view like that. I would simply write a custom reusable HTML helper:

public static class HtmlExtensions
{
    public static IHtmlString MyTextBoxFor<TModel, TProperty>(
        this HtmlHelper<TModel> htmlHelper,
        Expression<Func<TModel, TProperty>> ex,
        object htmlAttributes,
        bool disabled
    )
    {
        var attributes = new RouteValueDictionary(htmlAttributes);
        if (disabled)
        {
            attributes["disabled"] = "disabled";
        }

        return htmlHelper.TextBoxFor(ex, attributes);
    }
}

that you could use in the view as simply as:

@Html.MyTextBoxFor(m => model.value1, new { id = "blah" }, <condition>)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, still getting used to custom HtmlHelpers. Really useful info!
2

You have a scope issue with the above disable doesn't exist outside the scope of the if statement,

my recommendation is this:

@Html.TextBoxFor(m => model.value1, new { id = "blah", disabled = (<condition>) })

EDIT:

You can use

   @Html.TextBoxFor(m => model.value1, new { id = "blah", disabled = (<condition>) ? "disabled" : "" })

If you want to insert the word disabled rather than a bool, from memory this is kinda a browser specific setting some are happy with "true" others with "disabled"

3 Comments

This validates fine, but I think as im using the word "disabled" it automatically disables the box.
See my edit, you can use a ternary operator in-line to give different values based on an if statement.
disabled keyword automatically disables inputs

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.