-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxLengthTagHelper.cs
More file actions
49 lines (44 loc) · 1.74 KB
/
MaxLengthTagHelper.cs
File metadata and controls
49 lines (44 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace MaxLengthTagHelperDemo.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);
if (context.AllAttributes["maxlength"] == null) // Process only if 'maxlength' attr is not present
{
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;
}
}
}