具有自定义验证属性的 .NET MVC 错误客户端

本文关键字:NET MVC 错误 客户端 属性 自定义 验证 | 更新日期: 2023-09-27 18:31:49

我编写了一个非常简单的自定义验证属性来检查字母数字字符串,并且它正在服务器端工作,但是当尝试在.NET MVC中使用客户端模型验证时,我得到了验证上下文的NullReferenceException。我的自定义属性编写在 MVC 应用程序使用的单独类库中。 属性和验证器类如下所示:

/// <summary>
    /// Custom validation attribute for an alphanumeric string
    /// </summary>
    public class AlphaNumericAttribute : ValidationAttribute
    {
        public AlphaNumericAttribute()
            : base()
        {
            ErrorMessage = ValidationMessages.AlphaNumeric;
        }
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var RegExMatch = ValidationExpressions.AlphaNumeric.Match(value.ToString());
            if (!RegExMatch.Success)
            {
                return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
            }
            return null;
        }
    }
    /// <summary>
    /// Custom validator class for the AlphaNumeric attribute defined above.
    /// </summary>
    public class AlphaNumericValidator : DataAnnotationsModelValidator<AlphaNumericAttribute>
    {
        string errorMsg = string.Empty;
        public AlphaNumericValidator(ModelMetadata metadata,
        ControllerContext controllerContext, AlphaNumericAttribute attribute)
            : base(metadata, controllerContext, attribute) 
        {
            errorMsg = attribute.ErrorMessage;
        }
        public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
        {
            ModelClientValidationRule validationRule = new ModelClientValidationRule();
            validationRule.ValidationType = "alphanumeric";
            validationRule.ErrorMessage = Attribute.FormatErrorMessage(Metadata.DisplayName);
            return new[] { validationRule };
        }
    }

然后,我在我的 MVC 应用程序中有一个简单的模型类,其中包含使用 [AlphaNumeric] 装饰器的数据注释:

[Required, Display(Name = "Product Code"), AlphaNumeric]
        public string ProductCode { get; set; }

最后,我让我的控制器传递模型类并使用标准的 ModelState.IsValid 验证方式...

[HttpPost]
public ActionResult Index(CreateModel Model)
{
   if (ModelState.IsValid)
   {
      // Do some stuff
   }
   else return View(Model);
}

当我访问我的 Web 表单并提交时,在调用控制器的操作方法之前立即收到 null 引用异常:

[NullReferenceException: Object reference not set to an instance of an object.]
   LibData.Validation.AlphaNumericAttribute.IsValid(Object value, ValidationContext validationContext) +75
   System.ComponentModel.DataAnnotations.ValidationAttribute.GetValidationResult(Object value, ValidationContext validationContext) +29
   System.Web.Mvc.DataAnnotationsModelValidator.Validate(Object container) +372
   System.Web.Mvc.<Validate>d__1.MoveNext() +393
   System.Web.Mvc.DefaultModelBinder.OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext) +401
   System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) +123
   System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +2541
   System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +633
   System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +496
   System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +199
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__19(AsyncCallback asyncCallback, Object asyncState) +1680
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +59
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151
   System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +94
   System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +559
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1c(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState) +82
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +73
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151
   System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object callbackState, BeginInvokeDelegate`1 beginDelegate, EndInvokeVoidDelegate`1 endDelegate, TState invokeState, Object tag, Int32 timeout, SynchronizationContext callbackSyncContext) +105
   System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +588
   System.Web.Mvc.Controller.<BeginExecute>b__14(AsyncCallback asyncCallback, Object callbackState, Controller controller) +47
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +65
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151
   System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object callbackState, BeginInvokeDelegate`1 beginDelegate, EndInvokeVoidDelegate`1 endDelegate, TState invokeState, Object tag, Int32 timeout, SynchronizationContext callbackSyncContext) +139
   System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +484
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +50
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__4(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState) +98
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +73
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151
   System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object callbackState, BeginInvokeDelegate`1 beginDelegate, EndInvokeVoidDelegate`1 endDelegate, TState invokeState, Object tag, Int32 timeout, SynchronizationContext callbackSyncContext) +106
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +446
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +88
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +50
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

我在这里错过了什么? 如果我使用其他内置的数据注释,如正则表达式等。我没有收到此错误。 我是否需要向 MVC 应用程序注册某种处理程序? 我对此真的很茫然。 是的,我可以对这么简单的事情使用简单的正则表达式验证属性,但我需要了解问题的根源,因为我有许多更复杂的验证属性要编写,并且想了解如何适当地连接它们。 谢谢。。。

具有自定义验证属性的 .NET MVC 错误客户端

Rick,你确实需要一些额外的东西才能在客户端工作。这里有一个关于如何实现这一点的好教程:http://thewayofcode.wordpress.com/tag/custom-unobtrusive-validation/