2

I have a bool in my ViewModel called DisableNextButton and I would like to use it to disable a button in my view. I should add that this button lives inside an if statement.

Ultimately, I'm trying to add the disabled attribute when DisableNextButton is true.

Here's my unsuccessful implementation:

@if(true)
{
    <button type="button" @{ if (Model.DisableNextButton) { <text>disabled="disabled"</text> } } >Next</button>
}

I should note that this gives me a functioning enabled button.

lobsterhat
  • 157
  • 2
  • 4
  • 15

2 Answers2

8

Translated from this post:

<input type="button" value="Next" 
    @{
        if(Model.DisableNextButton)
        {
            @:disabled="disabled"
        }
    }
/>

Basically, the <text> tag is unnecessary, as this is not text, it's an HTML attribute.

Community
  • 1
  • 1
Codeman
  • 12,157
  • 10
  • 53
  • 91
  • Thanks for the post. I'm getting compile errors when using @: (I'm getting } expected in line 1 column 1). Would it matter that I'm nesting if statements in Razor? – lobsterhat Jun 25 '14 at 00:12
  • Do you have it exactly as typed? I don't have it open, so you may need to tweak it - line endings do matter in Razor, that's why I have it with a newline at the end. If this doesn't work and you find a tweak that does please post it as a comment and I will fix my post. – Codeman Jun 25 '14 at 00:14
  • No, I have everything on the same line. – lobsterhat Jun 25 '14 at 00:24
  • Thanks for the help. When I step through the code in my view, the `@disabled="disabled` line gets skipped over. I verified this by putting a dummy line after in the same if statement and that gets hit. Looks like the same thing is happening to the code in my original post. – lobsterhat Jun 25 '14 at 00:55
  • `@:disabled="disabled"` must be `@disabled="disabled"` – Rajshekar Reddy Sep 25 '14 at 16:54
2

I had similar issues with inline if:s to have / not have some html property. In the end i just went for the most basic. Mabey not the prettyes solution but it woorks.

@if (condition)
{
    <span id="true"></span>
}
else 
{
    <span id="false"></span>
}

After some small test this woorks aswell!

<span @(someBool ? "selected=selected" : "")>Cool </span>
SomeRandomName
  • 593
  • 1
  • 8
  • 23