简体   繁体   中英

Conditional Html attribute using razor

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?

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>

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:

  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 (eg: 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 (eg: 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

<!button @(Model.CanBeDeleted?"":"disabled='disabled'") 
type="button" class="btn btn-danger btn-sm">
  <span class="glyphicon glyphicon-trash"> </span> Delete
</!button>

You 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.

@code
    var enabled = "disabled='disabled'";
    if(Model.CanBeDeleted)
    enabled = "";
    end code
    <button Html.Raw(enabled) type="button" class="btn btn-danger btn-sm">
            <span class="glyphicon glyphicon-trash"> </span>
            Delete
        </button>

An example for Razor page Core 6.0.
The select is disabled when the User is not Authorized

@{
    var isAuthorized = await AuthorizationService.AuthorizeAsync(User, 
        null, Operations.ContractEdit);

    <div class="form-group">
        <label asp-for="Contract.Name" class="control-label">Contract</label>
        <select asp-for="Contract.Name" class="form-control"
            asp-items="ViewBag.ContractName"
            disabled="@(isAuthorized.Succeeded == false)"  
            >               
            <option selected value="">Select a contract name...</option>
        </select>                    
        <span asp-validation-for="Contract.Name" class="text-danger"></span>
    </div>
}

Thank You Kemuel Sanchez

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM