【发布时间】:2011-11-08 10:18:28
【问题描述】:
对于我的 ASP.NET MVC 项目,我创建了一个自定义验证属性。这是我正在努力的代码:
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 不包含任何可用的属性/方法来获取此信息。
-
这里有更多详细信息:stackoverflow.com/questions/7447932/…
标签: asp.net .net asp.net-mvc asp.net-mvc-3 asp.net-mvc-validation