Conditional Html attribute using razor

前端 未结 4 1743
故里飘歌
故里飘歌 2021-02-12 14:46

I have a situation where I want to display a button as being enabled or disabled depending on a property which has been set on the view model.

@if (Model.CanBeDe         


        
4条回答
  •  孤独总比滥情好
    2021-02-12 15:16

    Try this:

    
    

    Go ahead. Try it. You'll notice that when @Model.CanBeDeletedis false, the disable attribute is missing from the element. Conversely, when @Model.CanBeDeleted is true the disableelement is present, and is set to disable

    How does it work?

    It's thanks to Razor's "conditional attributes" feature. if you assign a razor variable to an atribute in your cshtml (or vbhtml) it will behave like this:

    1. If the variable or expression evaluates to null or false, it will ommit the attribute in the resulting html.
    2. If the variable or expression evaluates to true it will output the attribute AND will assign it a value equal to the name of the attribute (e.g.: disabled=disabled, checked=checked... you get the idea)
    3. If the variable or expression evaluates to a non-empty string it will assign it to the atribute as usual (e.g.: class="@myvar" => class="the_value_of_myvar")
    4. If the variable or expression evaluates to an empty string, it will output the attribute but won't assign any value.

    What I love about this sintax is that it greatly helps in keeping your razor views readable.

    You can read more about it in this article

提交回复
热议问题