2013-11-05 61 views
3

我想創建一個ErrorMessage,其中包含另一個變量或屬性值。 我想保持簡單。到目前爲止,這段代碼顯示了String.Format參數的錯誤。什麼是實現這一目標的最佳途徑:c#asp mvc ErrorMessage應該包含另一個變量/屬性值

public class MyClass 
    { 
     [RequiredIf("IsRequired", true, ErrorMessage=String.Format("The 'something' ({0}) is required because of: {1}", Something, CustomExplanation)] 
     public string Something { get; set; } 

     [Required] 
     public bool IsRequired { get; set; } 

     [Required] 
     [StringLength(200, MinimumLength=20)] 
     public string CustomExplanation { get; set; } 
    } 

我已經閱讀了這個問題,並回答:string.Format in Data Annotation Validation Attributes 這是確定的,但也許有一個解決辦法...

回答

4

我對你的建議是使用FluentValidator。這是實現你目標的非常好的圖書館。

鏈接 - http://fluentvalidation.codeplex.com/

您可以使用如下代碼解決您的問題:

RuleFor(m => m.Something).When(m => m.IsRequired).WithMessage("Your message here."); 

請讓我知道的情況下,或者如果你有問題。

相關問題