2010-04-07 84 views
2

我正在編寫PropertiesMustMatch驗證屬性,它可以將字符串屬性名稱作爲參數。我希望它通過該對象上的名稱找到相應的屬性並進行基本的平等比較。 通過反思訪問這個最好的方法是什麼?如何檢索屬性關聯對象的實例?

此外,我檢查了企業庫中的驗證應用程序塊,並確定其PropertyComparisonValidator對於我們所需的東西來說過於激烈。

更新:爲了進一步說明(提供一些上下文),目標僅僅是驗證實施字段匹配(例如,密碼驗證)。如果可能的話,我們希望它使用繼承自ValidationAttribute類的屬性級屬性數據註釋。

UPDATE:如果有人好奇,我最終通過調整作爲一個答案提供的代碼本question

回答

4

基本上,你不能。檢查對象是否存在屬性的代碼還必須承擔責任,告訴任何代碼它正在查看的類型/對象。您無法從獲取屬性中的任何其他元數據。

+0

有沒有最好的解決方法呢?不幸的是,它並不像這樣簡單:'[MustMatchValidator(this,「FieldToMatch」)]' – 2010-04-07 20:01:51

+0

@Brandon:nope。 – 2010-04-07 20:04:27

+0

感謝您的信息 – 2010-04-08 02:20:31

1

你不能這樣做,解決實際的業務問題。另見this question。嘗試改變邏輯來處理對象,檢查其屬性,而不是相反。您還可以提供有關您的任務的更多信息,而不僅僅是這個狹窄的問題。

+0

請參閱我的說明更新 – 2010-04-07 20:07:03

0

你可以這樣。

//target class 
public class SomeClass{ 

    [CustomRequired(ErrorMessage = "{0} is required", ProperytName = "DisplayName")] 
    public string Link { get; set; } 

    public string DisplayName { get; set; } 
} 
//custom attribute 
public class CustomRequiredAttribute : RequiredAttribute, IClientValidatable 
{ 
    public string ProperytName { get; set; } 

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) 
    { 
    var propertyValue = "Value"; 
    var parentMetaData = ModelMetadataProviders.Current 
     .GetMetadataForProperties(context.Controller.ViewData.Model, context.Controller.ViewData.Model.GetType()); 
    var property = parentMetaData.FirstOrDefault(p => p.PropertyName == ProperytName); 
    if (property != null) 
     propertyValue = property.Model.ToString(); 

    yield return new ModelClientValidationRule 
    { 
     ErrorMessage = string.Format(ErrorMessage, propertyValue), 
     ValidationType = "required" 
    }; 
    } 
} 
相關問題