對於我的ASP.NET MVC項目,我創建了一個自定義驗證屬性。這裏是我掙扎代碼:自定義驗證:從validationContext獲取屬性名稱
protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
//Here I need to resolve the url in order to make a call to that controller action and get the JSON result back
var httpContext = new HttpContextWrapper(HttpContext.Current);
var urlHelper = new UrlHelper(
new System.Web.Routing.RequestContext(
httpContext, new System.Web.Routing.RouteData()
)
);
var url = urlHelper.Action(Action, Controller, null,
urlHelper.RequestContext.HttpContext.Request.Url.Scheme);
var fullUrl = string.Format("{0}?{1}={2}", url,
/*validationContext.MemberName*/"term", value);
if (!GetResult(fullUrl)) {
var message = FormatErrorMessage(validationContext.DisplayName);
return new ValidationResult(message);
}
return null;
}
你可以看到從下面鏈接的完整代碼:
對於fullUrl
變量,我想追加的屬性名稱的查詢字符串但是當我使用validationContext.MemberName
時,我失敗了。我通過將臨時修復作爲「術語」來解決這個問題,但它根本不是一個解決方案。
那麼,從validationContext
檢索屬性名稱的方法是什麼?
我有同樣的問題。我甚至想更進一步,並獲得所有被驗證屬性的CustomAttributes。令人遺憾的是,validationContext不包含任何可用的屬性/方法來獲取此信息。 – Peter
這裏回答更詳細的: http://stackoverflow.com/questions/7447932/mvc-3-model-validation-issue-oversight-or-by-design –