How to disable a button more elegantly

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?

Answers


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" 
        } }
/>

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>

try this

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

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)

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

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


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

Need Your Help

Variable Explorer freezes when viewing tuples in python Spyder IDE

python python-2.7 tuples anaconda spyder

I am having a problem with the Variable Explorer in Anaconda 1.9.2 (64-bit) Spyder 2.2.5, Python 2.7

Deleting Multiple selected items from table

cakephp checkbox controller

In my table I have a column with a check box for each row. I want to be able to delete all the selected items. I found the code from this website and modified it for my own stuff.