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.CanBeDeleted)
{
<button type="button" class="btn btn-danger btn-sm">
<span class="glyphicon glyphicon-trash"> </span>
Delete
</button>
}
@if (!Model.CanBeDeleted)
{
<button disabled="disabled" type="button" class="btn btn-danger btn-sm">
<span class="glyphicon glyphicon-trash"> </span>
Delete
</button>
}
The code currently in my view, which can be seen above, does work.
However, I am looking for a way that I can wrap only the disabled
attribute in the if statement rather than having a separate button element for each case.
Any suggestions for how I can do this?
Try this:
Go ahead. Try it. You'll notice that when
@Model.CanBeDeleted
is false, thedisable
attribute is missing from the element. Conversely, when@Model.CanBeDeleted
is true thedisable
element is present, and is set todisable
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
(orvbhtml
) it will behave like this:disabled=disabled
,checked=checked
... you get the idea)class="@myvar"
=>class="the_value_of_myvar
")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
You can use
@Html.Raw
to inject markup directly into elementsYou can Opt out individual elements from being evaluated as a TagHelper with !(Exclamation Point)
In its current form, Razor TagHelpers don't allow you to insert attributes by including the string literal of the attribute you want to insert.
Do the check once and have the disabled property be determined by a temporary variable called enabled.