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?
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>
Possible easy way:
<input type="button" @(item.PMApproved ? "disabled" : "") />
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