首页 > 解决方案 > Asp.net core mvc如何通过剃刀设置属性“必需”

问题描述

我在 mvc 中有一个表单,其中不同的字段设置是从数据库控制的。

我编写了一个 razor 函数来检查某些字段是否是必需的。

如果为真,我需要设置所需的属性。目前我无法在输入标签中调用 razor 函数。

我有哪些选择?

<input type="text" class="form-control" asp-for="@Model.Title" required="@myfunction()" maxlength="200" />

标签: c#asp.net-mvcrazorasp.net-core-mvc

解决方案


您可以为这种情况创建一个标签助手,如下所示

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

有关标记助手的更多信息,请使用此链接


推荐阅读