【问题标题】:MaxLength annotation to maxlength input property对 maxlength 输入属性的 MaxLength 注释
【发布时间】:2017-04-18 16:32:14
【问题描述】:

在 ASP.NET Core 1.1 中使用以下 DataAnnotations。最好在我的 MVC 视图中设置输入的最大长度以限制用户输入。

型号

[Display(Name = "Post Code")]
[MaxLength(8, ErrorMessage = "Maximum number of characters that can be entered is 8!")]
public string PostCode
{ get; set; }

查看

<label asp-for="PostCode"></label>
<input style="font-weight: normal;" class="form-control" placeholder="Post Code" asp-for="PostCode" data-val="true" autofocus />

呈现为

<input style="font-weight: normal;" class="form-control valid" placeholder="Post Code" data-val="true" autofocus="" type="text" data-val-maxlength="Maximum number of characters that can be entered is 8!" data-val-maxlength-max="8" id="PostCode" name="PostCode" value="" wtx-context="FA5749C8-68AC-44FE-88B9-4BBDF9D48DAE" aria-invalid="false" aria-describedby="PostCode-error">

我想从我的类数据注释中生成 maxlength 属性,如下所示。 (滚动到结尾);

<input style="font-weight: normal;" class="form-control valid" placeholder="Post Code" data-val="true" autofocus="" type="text" data-val-maxlength="Maximum number of characters that can be entered is 8!" data-val-maxlength-max="8" id="PostCode" name="PostCode" value="" wtx-context="FA5749C8-68AC-44FE-88B9-4BBDF9D48DAE" aria-invalid="false" aria-describedby="PostCode-error" maxlength="8">

感谢任何建议。

【问题讨论】:

  • 无论如何,当你的意思是“ASP.NET Core”时,请停止使用“.NET Core”。 .NET Core 是一个运行时,而 ASP.NET Core 是一个 webstack,它运行在 .NET Core 或完整的 .NET Framework 之上
  • 如果设置了 max-length 属性,您甚至不需要设置 data-val-maxlength 错误消息,因为用户不可能超过最大长度。 :-)

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


【解决方案1】:

您可能需要通过 TagHelper 来实现此功能,它可以读取此属性并在呈现时将其添加到元素中,因为默认的 asp-for 不会处理此问题。

扩展输入 TagHelper

尝试在您的项目中按如下方式声明 TagHelper,这将扩展现有的 asp-for 帮助器并处理读取任何现有属性/元数据并将必要的属性附加到元素:

namespace YourProject.TagHelpers
{
    [HtmlTargetElement("input", Attributes = "asp-for")]
    public class MaxLengthTagHelper : TagHelper
    {
        public override int Order { get; } = 999;

        [HtmlAttributeName("asp-for")]
        public ModelExpression For { get; set; }

        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            base.Process(context, output);

            // Process only if 'maxlength' attr is not present
            if (context.AllAttributes["maxlength"] == null) 
            {
                // Attempt to check for a MaxLength annotation
                var maxLength = GetMaxLength(For.ModelExplorer.Metadata.ValidatorMetadata);
                if (maxLength > 0)
                {
                    output.Attributes.Add("maxlength", maxLength);
                }
            }
        }

        private static int GetMaxLength(IReadOnlyList<object> validatorMetadata)
        {
            for (var i = 0; i < validatorMetadata.Count; i++)
            {
                var stringLengthAttribute = validatorMetadata[i] as StringLengthAttribute;
                if (stringLengthAttribute != null && stringLengthAttribute.MaximumLength > 0)
                {
                    return stringLengthAttribute.MaximumLength;
                }

                var maxLengthAttribute = validatorMetadata[i] as MaxLengthAttribute;
                if (maxLengthAttribute != null && maxLengthAttribute.Length > 0)
                {
                    return maxLengthAttribute.Length;
                }
            }
            return 0;
        }
    }
}

使用 TagHelper

然后直接在您的特定视图中或在_ViewImports.cshtml 文件中全局添加对其的引用,如下所示:

@using YourProject
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, YourProject

添加后,此扩展 TagHelper 应自动使用适当的 maxlength 属性装饰您的元素(如果存在于您的属性中):

<!-- Input -->
<label asp-for="PostCode"></label>
<input style="font-weight: normal;" class="form-control" placeholder="Post Code" asp-for="PostCode" data-val="true" autofocus />

<!-- Rendered -->
<label for="PostCode">Post Code</label>
<input style="font-weight: normal;" class="form-control" placeholder="Post Code" data-val="true" autofocus="" type="text" data-val-maxlength="Maximum number of characters that can be entered is 8!" data-val-maxlength-max="8" id="PostCode" name="PostCode" value="" maxlength="8">

【讨论】:

  • 完美 - 魅力十足 - 感谢 Rion!
  • 这很好,因为它已经考虑了 maxLength 和 stringLength 属性。我通过验证 minLength 属性和由可能的范围属性设置(即 Range(2000,2099) => maxLength = 4)产生的 maxLength 来扩展这个 TagHelper,并将其用作 CustomInputTagHelper。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-29
  • 2012-05-20
  • 2020-03-22
  • 2012-07-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多