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?
The If Condition The if statement returns true or false, based on your test: The if statement starts a code block. The condition is written inside parenthesis. The code inside the braces is executed if the test is true.
New @model directive Let's now look at a new feature we added with the ASP.NET MVC 3 Beta – the @model directive. The @model directive provides a cleaner and more concise way to reference strongly-typed models from view files.
Razor is a markup syntax for embedding . NET based code into webpages. The Razor syntax consists of Razor markup, C#, and HTML. Files containing Razor generally have a . cshtml file extension.
Try this:
<button type="button" class="btn btn-danger btn-sm" disabled="@Model.CanBeDeleted"> <span class="glyphicon glyphicon-trash"> </span> Delete </button>
Go ahead. Try it. You'll notice that when @Model.CanBeDeleted
is false, the disable
attribute is missing from the element. Conversely, when @Model.CanBeDeleted
is true the disable
element 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:
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 elements
<button @Html.Raw(Model.CanBeDeleted?"":"disabled='disabled'") type="button" class="btn btn-danger btn-sm"> <span class="glyphicon glyphicon-trash"> </span> Delete </button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With