如何更优雅禁用按钮(How to disable a button more elegantly)

2019-06-23 15:59发布

我有我的观点如下剃刀代码之一:

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

相当粗糙。 基本上,我想在一定条件下,禁用按钮,你可以从代码中锻炼身体。 什么是这样做的更为可取的办法?

Answer 1:

我不知道你使用的是什么语言,但你也许可以将您if更接近语句的两条线之间的实际差异:

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


Answer 2:

通过一个新的扩展方法计算机辅助一种标记为中心的解决方案:

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

在您的看法,重用了wazoo:

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

奈斯利可重复使用,且呈现标记很干净,关于空白:

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


Answer 3:

试试这个

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


Answer 4:

一个助手可以帮助:

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));
    }
}

然后:

@Html.ApproveButton(item)


Answer 5:

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

没有必要的臃肿的代码,只是保持简单:-)



Answer 6:

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


文章来源: How to disable a button more elegantly