ASP.Net Core MVC – 自定义属性的客户端validation
在以前版本的MVC框架中,将通过实现IClientValidatable
和GetClientValidationRules
方法来实现自定义validation。
但是在ASP.Net Core MVC中我们没有这个接口 ,尽管我们确实有IClientModelValidator
,它定义了一个非常相似的方法。 然而,其实现永远不会被调用。
那么 – 我们如何在ASP.NET Core MVC中为自定义属性实现客户端validation?
IClientModelValidator
实际上是正确的接口。 我在下面做了一个人为的示例实现。
注意: RC1和RC2之间的IClientModelValidator
接口发生了重大变化 。 两个选项如下所示 – 其余代码在两个版本之间是相同的。
上述就是C#学习教程:ASP.Net Core MVC – 自定义属性的客户端validation分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
属性(RC2及以上)
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] public sealed class CannotBeRedAttribute : ValidationAttribute, IClientModelValidator { public override bool IsValid(object value) { var message = value as string; return message?.ToUpper() == "RED"; } public void AddValidation(ClientModelValidationContext context) { MergeAttribute(context.Attributes, "data-val", "true"); var errorMessage = FormatErrorMessage(context.ModelMetadata.GetDisplayName()); MergeAttribute(context.Attributes, "data-val-cannotbered", errorMessage); } private bool MergeAttribute( IDictionary attributes, string key, string value) { if (attributes.ContainsKey(key)) { return false; } attributes.Add(key, value); return true; } }
属性(RC1)
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] public sealed class CannotBeRedAttribute : ValidationAttribute, IClientModelValidator { public override bool IsValid(object value) { var message = value as string; return message?.ToUpper() == "RED"; } public IEnumerable GetClientValidationRules( ClientModelValidationContext context) { yield return new ModelClientValidationRule( "cannotbered", FormatErrorMessage(ErrorMessage)); } }
模型
public class ContactModel { [CannotBeRed(ErrorMessage = "Red is not allowed!")] public string Message { get; set; } }
视图
@model WebApplication22.Models.ContactModel @section scripts { }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1000753.html