问题
I have a button in my view which I would like to be disabled based on certain condition. Below is my view:
@{
var myCondition = false;
myCondition = //set condtion here
}
<input type="submit" value="Create" class=" btn btn-primary" />
So based on myCondition I want to disabled/enable my button.
I can do like:
@if(myCondition)
{
<input type="submit" value="Create" disabled="disabled" class=" btn btn-primary" />
}
else
{
//enable it here
}
Is there any elegant way to do that in .net core. Can we use some htmlextensions here. If someone can give me an example pls.
Inputs are appreciated.
回答1:
You can create html helper as:
public static class HtmlExtensions
{
public static IHtmlContent DisabledIf(this IHtmlHelper htmlHelper,
bool condition)
=> new HtmlString(condition ? "disabled=\"disabled\"" : "");
}
Then in your view:
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<input type="submit" value="Create" class=" btn btn-primary" @Html.DisabledIf(yourcondition) />
回答2:
If you do not like to conditionally render the button in the view, you can build a tag helper to do so.
[HtmlTargetElement("button")]
public class MyDisablableButton : TagHelper
{
[HtmlAttributeName("asp-is-disabled")]
public bool IsDisabled { set; get; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
if (IsDisabled)
{
var d = new TagHelperAttribute("disabled", "disabled");
output.Attributes.Add(d);
}
base.Process(context, output);
}
}
Now to use this custom tag helper, you need to call the addTagHelper
method in _ViewImports.cshtml
.
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, YourAssemblyNameHere
Now you can use it in views like
<button asp-is-disabled="true">Save</button>
<button asp-is-disabled="false">Save</button>
<button asp-is-disabled="@yourBooleanVariable">Save</button>
来源:https://stackoverflow.com/questions/47076119/conditionally-render-disabled-button-in-asp-net-core-view