[英]How can I retrieve the instance of an attribute's associated object?
我正在編寫一個PropertiesMustMatch
驗證屬性,該屬性可以將字符串屬性名稱作為參數。 我想按名稱在該對象上找到相應的屬性,然后進行基本的相等比較。 通過反射訪問此內容的最佳方法是什么?
另外,我檢查了企業庫中的Validation應用程序塊,並確定其PropertyComparisonValidator對於我們所需的內容過於緊張。
更新:為了進一步澄清(以提供一些上下文),目標只是驗證,以強制執行字段匹配(例如,密碼驗證)。 如果可能的話,我們希望它可以使用從ValidationAttribute
類繼承的屬性級屬性數據注釋。
更新:萬一有人好奇,我最終通過調整代碼來解決實際的業務問題,以解決該問題。
基本上你不能。 檢查對象是否存在屬性的代碼還必須承擔告訴任何代碼其正在查看的類型/對象的責任。 你無法從屬性中獲得任何額外的元數據。
你不能這樣做。 另請參閱此問題 。 嘗試更改用於對象的邏輯,檢查其屬性,反之亦然。 您還可以提供有關任務的更多信息,而不僅僅是這個狹窄的問題。
你可以這樣。
//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"
};
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.