How to disable a button more elegantly

2020-02-09 06:50发布

问题:

I have on one of my views the following razor code:

@if (item.PMApproved != true) {
                    <input type="button" class="btnresetinvoice button" value="Reset" data-invoiceid="@item.InvoiceId" />
                }
                else {
                    <input type="button" class="btnresetinvoice button" value="Reset" data-invoiceid="@item.InvoiceId" disabled="disabled" />
                }

Pretty rough. Basically I want to disable the button under a certain condition as you'd be able to work out from the code. What would be a more desirable way of doing this?

回答1:

I don't know what language you're using, but you might be able to move your if statement closer to the actual different between the two lines:

<input type="button" class="btnresetinvoice button" value="Reset"
       data-invoiceid="@item.InvoiceId"
       @{ if(item.PMApproved != true) { 
             @:disabled="disabled" 
        } }
/>


回答2:

A markup-centric solution aided by a new extension method:

public static class HtmlExtensions
{
   public static HtmlString DisabledIf(this HtmlHelper html, bool condition)
   {
      return new HtmlString(condition ? "disabled=\"disabled\"" : "");
   }
}

In your views, reuse out the wazoo:

<button type="reset" @Html.DisabledIf(someCondition)>Clear Fields</button>

Nicely reusable, and the rendered markup is very clean with regards to whitespace:

<button type="reset" disabled="disabled">Clear Fields</button>


回答3:

try this

<button type="submit" disabled="@(!item.PMApproved)"></button>


回答4:

A helper could help:

public static class HtmlExtensions
{
    public static IHtmlString ApproveButton(this HtmlHelper htmlHelper, MyViewModel item)
    {
        var button = new TagBuilder("input");
        button.Attributes["type"] = "button";
        button.Attributes["value"] = "Reset";
        button.AddCssClass("btnresetinvoice");
        button.AddCssClass("button");
        button.Attributes["data-invoiceid"] = item.InvoiceId.ToString();
        if (item.PMApproved)
        {
            button.Attributes["disabled"] = "disabled";
        }
        return new HtmlString(button.ToString(TagRenderMode.SelfClosing));
    }
}

and then:

@Html.ApproveButton(item)


回答5:

<input type="button" value="Reset" @{@((!item.PMApproved) ? null : new { disabled = "disabled" })}; />

No need for that bloated code, just keep it simple :-)



回答6:

<button @(isEnabled ? null : "disabled")>Butt</button>


回答7:

Possible easy way:

<input type="button" @(item.PMApproved ? "disabled" : "") />


回答8:

Using asp.net mvc5 razor:

@if(condition)
{
   <button data-toggle="collapse" data-target="#content">Details</button>
}
else
{
   <button disabled>Details</button>
}

It prevents attempting to enable button from DevTools, because razor not visible for DevTools