2011-08-30 43 views
0

我試圖對我的某個視圖模型使用Simon Ince's conditional validation attributes。這個邏輯看起來很有用,但該屬性的錯誤消息並未出現在我的視圖的ValidationFor()方法中。ASP.NET MVC 2 - 使用Simon Ince的條件驗證屬性時,驗證屬性錯誤消息沒有顯示在我的視圖中

屬性:

public class RequiredIfAttribute : ValidationAttribute 
{ 
    private RequiredAttribute innerAttribute = new RequiredAttribute(); 
    public string DependentProperty { get; set; } 
    public object TargetValue { get; set; } 

    public RequiredIfAttribute(string dependentProperty, object targetValue) 
    { 
     this.DependentProperty = dependentProperty; 
     this.TargetValue = targetValue; 
    } 

    public override bool IsValid(object value) 
    { 
     return innerAttribute.IsValid(value); 
    } 
} 

的驗證:

public class RequiredIfValidator : DataAnnotationsModelValidator<RequiredIfAttribute> 
{ 
    public RequiredIfValidator(ModelMetadata metadata, ControllerContext context, RequiredIfAttribute attribute) 
     : base(metadata, context, attribute) 
    { 
    } 

    public override IEnumerable<ModelClientValidationRule> GetClientValidationRules() 
    { 
     // no client validation - I might well blog about this soon! 
     return base.GetClientValidationRules(); 
    } 

    public override IEnumerable<ModelValidationResult> Validate(object container) 
    { 
     // get a reference to the property this validation depends upon 
     var field = Metadata.ContainerType.GetProperty(Attribute.DependentProperty); 

     if (field != null) 
     { 
      // get the value of the dependent property 
      var value = field.GetValue(container, null); 

      // compare the value against the target value 
      if ((value == null && Attribute.TargetValue == null) || 
       (value.Equals(Attribute.TargetValue))) 
      { 
       // match => means we should try validating this field 
       if (!Attribute.IsValid(Metadata.Model)) 
        // validation failed - return an error 
        yield return new ModelValidationResult { Message = ErrorMessage }; 
      } 
     } 
    } 
} 

他們怎麼勾搭上了(Global.asax.cs中):

public class MvcApplication : System.Web.HttpApplication 
{ 
    public static void RegisterRoutes(RouteCollection routes) 
    { 
     routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

     routes.MapRoute(
      "Default", // Route name 
      "{controller}/{action}/{id}", // URL with parameters 
      new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults 
     ); 

    } 

    protected void Application_Start() 
    { 
     AreaRegistration.RegisterAllAreas(); 
     RegisterRoutes(RouteTable.Routes); 
     ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory()); 
     DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false; 
     DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredIfAttribute), typeof(RequiredIfValidator)); 
    } 
} 

怎麼我試圖使用它:

public class AdminGameViewModel 
{ 
    public bool IsCreated { get; set; } 

    [Required] 
    public int GameID { get; set; } 

    [Required(ErrorMessage = "A game must have a title")] 
    [DisplayFormat(ConvertEmptyStringToNull=false)] 
    public string GameTitle { get; set; } 

    [Required(ErrorMessage = "A short URL must be supplied")] 
    [DisplayFormat(ConvertEmptyStringToNull=false)] 
    public string Slug { get; set; } 

    [RequiredIf("IsCreated", true, ErrorMessage = "A box art image must be supplied")] 
    public HttpPostedFileBase BoxArt { get; set; } 

    [RequiredIf("IsCreated", true, ErrorMessage = "A large image for the index page is required")] 
    public HttpPostedFileBase IndexImage { get; set; } 

    // other props of the class.... 
} 

我不太瞭解MVC驗證機制的內部工作原理,以便解決我的問題。有任何想法嗎?

回答

1

您是否嘗試更新到我的MVC3實施?它比MVC2中的驗證器所需的破解更清晰。

即使是MVC3代碼也缺少一件事,那就是需要重寫屬性上的FormatErrorMessage,這可能與您在這裏看到的類似。對於我使用的MVC 3代碼;

public override string FormatErrorMessage(string name) 
    { 
     if (!String.IsNullOrEmpty(this.ErrorMessage)) 
      innerAttribute.ErrorMessage = this.ErrorMessage; 
     return innerAttribute.FormatErrorMessage(name); 
    } 

HTH 西蒙

+0

我沒有,只是因爲我的MVC 2項目即將完成90%。我正在點擊「我」,穿越「T」舞臺的大部分事情。不過,升級到MVC 3肯定會發生。感謝您花時間看看它......我會根據您上面提供的內容查看是否可以使錯誤消息生效。 –

相關問題