use*_*677 2 asp.net-core-mvc asp.net-core
我的视图中有一个按钮,我希望根据某些条件禁用该按钮。以下是我的看法:
@{
var myCondition = false;
myCondition = //set condtion here
}
<input type="submit" value="Create" class=" btn btn-primary" />
Run Code Online (Sandbox Code Playgroud)
因此,根据 myCondition 我想禁用/启用我的按钮。
我可以这样做:
@if(myCondition)
{
<input type="submit" value="Create" disabled="disabled" class=" btn btn-primary" />
}
else
{
//enable it here
}
Run Code Online (Sandbox Code Playgroud)
在 .net core 中是否有任何优雅的方法可以做到这一点。我们可以在这里使用一些 htmlextensions 吗?如果有人可以给我一个例子。
感谢您的投入。
如果您不喜欢在视图中有条件地呈现按钮,您可以构建一个标签助手来执行此操作。
[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);
}
}
Run Code Online (Sandbox Code Playgroud)
现在要使用这个自定义标签助手,您需要调用addTagHelper中的方法_ViewImports.cshtml。
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, YourAssemblyNameHere
Run Code Online (Sandbox Code Playgroud)
现在您可以在类似的视图中使用它
<button asp-is-disabled="true">Save</button>
<button asp-is-disabled="false">Save</button>
<button asp-is-disabled="@yourBooleanVariable">Save</button>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6999 次 |
| 最近记录: |