JustAnotherDeveloper
JustAnotherDeveloper

Reputation: 3199

Additional parameters for TextBoxFor() in ASP.net MVC3

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?

Upvotes: 1

Views: 7162

Answers (2)

undefined
undefined

Reputation: 34309

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"

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1039498

@{
    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>)

Upvotes: 3

Related Questions