1

I'm trying to toggle between enabling or disabling an html button from a Razor view based on an if statement. This disables the button regardless of the value of the if statement.

@{
    disabled = "";
    if (Model.User.PublicId == ViewBag.SiteUser.PublicId)
    {
        followClass += " you";
        followText = "You";
        disabled = "disabled";
    }
}

<button class="@followClass" disabled="@(disabled)">@(followText)</button>
1
  • 1
    BTW, you can get rid of all of those parentheses. Commented Dec 16, 2013 at 19:03

2 Answers 2

2

Simple fix, just remove disabled="" from the button definition.

<button class="@followClass" @disabled >@followText</button>
Sign up to request clarification or add additional context in comments.

2 Comments

Disabled is a boolean attribute - see developer.mozilla.org/en-US/docs/Web/HTML/Element/Input - the presence of the attribute indicates that the control is disabled - "disabled" by itself is the same as disabled="disabled". As you have discovered removing the attribute will enable the control.
This must not be allowed anymore. I get unhandled exception rendering component: Failed to execute 'setAttribute' on 'Element': '@disabled' is not a valid attribute name.
0

If you want to keep the disabled in the button definition you can do the following:

<button @if (@Model.DisableButtonModel) {  @("disabled='1'") }>My Button</button>

Comments

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.