2014-11-24 91 views
-1

我已經寫了一個非常簡單的自定義驗證屬性來檢查字母數字字符串,它是工作服務器端,但我嘗試使用客戶端模型時,獲取NullReferenceException validationContext .NET MVC中的驗證。我的自定義屬性被寫入MVC應用程序使用的單獨的類庫中。屬性和校驗器類在這裏:.NET MVC錯誤客戶端與自定義驗證屬性

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

最後,我有我的控制器是:

/// <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應用程序通過模型類,並使用驗證的標準ModelState.IsValid方式...

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

當我進入我的網頁表單並提交,我立即得到空引用異常之前控制器的行動方法曾被稱爲:

[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應用程序註冊某種處理程序?我對此感到不知所措。是的,我可以使用一個簡單的正則表達式驗證屬性來實現這個簡單的事情,但是我需要理解問題的根源,因爲我有許多更復雜的驗證屬性可供編寫,並且想要了解如何正確連接它們。謝謝...

回答

0

瑞克,你確實需要一些額外的東西在客戶端工作。 這裏是一個很好的教程,如何實現這個:http://thewayofcode.wordpress.com/tag/custom-unobtrusive-validation/

+0

感謝您的迴應。事實證明,這是服務器端驗證,因爲我沒有在視圖中用Html.BeginForm()幫助器創建我的表單,而Html.BeginForm()幫助器需要綁定validationContext。我只是創建自己的表單標籤。 – 2014-11-24 19:12:59

+0

我說得太快了 - 我仍然遇到使用自定義屬性的錯誤,我只想做服務器端驗證。 – 2014-11-24 21:52:12

+0

@RickClift - 您可能需要將返回值從null更改爲IsValid方法上的ValidationResult對象。你應該總是返回一個對象而不是null。 – Eduardo 2014-11-24 22:28:16

相關問題