By using bruce's link, I made a demo for you to refer, if you have any questions, welcome to post your questions:
CustomTagHelper:
[HtmlTargetElement("input", Attributes = "asp-for")]
public class CustomTagHelper : TagHelper
{
public override int Order { get; } = int.MaxValue;
[HtmlAttributeName("asp-for")]
public ModelExpression For { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
base.Process(context, output);
if (context.AllAttributes["data-maxsize"] == null)
{
var maxLength = GetMaxLength(For.ModelExplorer.Metadata.ValidatorMetadata);
if (maxLength > 0)
{
output.Attributes.Add("data-maxsize", maxLength);
}
}
if (context.AllAttributes["accept"] == null)
{
string[] allowed = Getallowed(For.ModelExplorer.Metadata.ValidatorMetadata);
if (allowed !=null)
{
string allowed1 = string.Join(",", allowed); //convert array to string
output.Attributes.Add("accept",allowed1);
}
}
}
private static int GetMaxLength(IReadOnlyList<object> validatorMetadata)
{
for (var i = 0; i < validatorMetadata.Count; i++)
{
if (validatorMetadata[i] is MaxFileSizeAttribute maxFileSizeAttribute && maxFileSizeAttribute.maxFileSizeInBytes > 0)
{
return maxFileSizeAttribute.maxFileSizeInBytes;
}
}
return 0;
}
private static string[] Getallowed(IReadOnlyList<object> validatorMetadata)
{
for (var i = 0; i < validatorMetadata.Count; i++)
{
if (validatorMetadata[i] is AllowedExtensionsAttribute allowedExtensionsAttribute && allowedExtensionsAttribute.allowedExtensions!=null)
{
return allowedExtensionsAttribute.allowedExtensions;
}
}
return null;
}
}
CustomAttribute class (almost the same like another):
public class AllowedExtensionsAttribute : ValidationAttribute
{
public string[] allowedExtensions;
public AllowedExtensionsAttribute(string[] allowedExtensions)
{
this.allowedExtensions = allowedExtensions;
}
}
Result:
Best Regards,
Jerry Cai
.NET forums are moving to a new home on Microsoft Q&A, we encourage you to go to Microsoft Q&A for .NET for posting new questions and get involved today.
Participant
780 Points
267 Posts
Re: Read custom data annotation and its parameters on View
Oct 26, 2020 08:25 AM|Jerry Cai|LINK
Hi,vkagrawal
By using bruce's link, I made a demo for you to refer, if you have any questions, welcome to post your questions:
CustomTagHelper:
CustomAttribute class (almost the same like another):
public class AllowedExtensionsAttribute : ValidationAttribute { public string[] allowedExtensions; public AllowedExtensionsAttribute(string[] allowedExtensions) { this.allowedExtensions = allowedExtensions; } }
Result:
Best Regards,
Jerry Cai