MaxLength注释为maxlength输入属性 [英] MaxLength annotation to maxlength input property

查看:239
本文介绍了MaxLength注释为maxlength输入属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Using the following DataAnnotations in ASP.NET Core 1.1. It would be good to have the max length of the input in my MVC View to be set to restrict the users input.

模型

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

我想按照以下说明从我的班级数据注释中生成属性. (滚动到结束);

I am wanting to generate the maxlength attribute from my class data annotation as per the below. (scroll to end);

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

感谢任何建议.

推荐答案

您可能需要通过TagHelper来实现此功能,该功能可以读取此属性,并在呈现时将其添加到元素中,因为默认的asp-for会赢"不能解决这个问题.

You may need to implement this functionality via a TagHelper which can read this attribute and add it to the element when rendered, as the default asp-for one won't handle this.

扩展输入TagHelper

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

Try declaring a TagHelper as follows within your project, which will etend the existing asp-for helper and handle reading any existing attributes / metadata and appending the necessary attributes to the element:

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文件中添加对其的引用,如下所示:

Then add a reference to it, either directly in your specific view, or globally in the _ViewImports.cshtml file as seen below:

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

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

Once added, this extended TagHelper should automatically decorate your element with the appropriate maxlength attribute, if present on your property:

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

这篇关于MaxLength注释为maxlength输入属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆