c# - Asp.net core mvc如何通过剃刀设置属性“必需”
问题描述
我在 mvc 中有一个表单,其中不同的字段设置是从数据库控制的。
我编写了一个 razor 函数来检查某些字段是否是必需的。
如果为真,我需要设置所需的属性。目前我无法在输入标签中调用 razor 函数。
我有哪些选择?
<input type="text" class="form-control" asp-for="@Model.Title" required="@myfunction()" maxlength="200" />
解决方案
您可以为这种情况创建一个标签助手,如下所示
private const string ForAttributeName = "asp-for";
[HtmlAttributeName("asp-is-required")]
public bool IsMandatory { set; get; }
public InputTextRequired(IHtmlGenerator generator) : base(generator)
{
}
public override void Process(TagHelperContext context, TagHelperOutput output)
{
if (IsMandatory)
{
var attribute = new TagHelperAttribute("required");
output.Attributes.Add(attribute);
}
base.Process(context, output);
}
}
您可以在输入标签中使用该标签助手,如下所示
<input type="text" class="form-control" asp-for="@Model.Title" asp-is-required="true/false from razor" maxlength="200" />
有关标记助手的更多信息,请使用此链接
推荐阅读
- vue.js - 未捕获的 ReferenceError:Vue Js 中的 webpackJsonp
- javascript - 将稀疏对象转换为嵌套对象
- solidity - 如何使用具有不同编译指示/编译器版本的导入来开发和编译安全帽?
- python - 如何更新画布“进度”栏?
- autodesk-forge - Forge 查看器:如何隔离自定义对象?
- indexing - Rust: 不能使用 HashMap::
- oracle - Oracle PLSQL - 声明子类型不为空
- python - SetDIBitsToDevice() 太慢?
- javascript - 通过js加载xml内容
- c++ - 关于在另一个类中保留对 unique_ptr 的引用的问题