Custom Validation : get the property name from validationContext

6.6k Views Asked by At

For my ASP.NET MVC projects, I created a custom validation attribute. Here is the code I am struggling with :

  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;
    }

You can see the full code from below link :

https://bitbucket.org/tugberk/tugberkug.mvc/src/6cc3d3d64721/TugberkUg.MVC/Validation/ServerSideRemoteAttribute.cs

For the fullUrl variable, I am trying to append the property name to querystring but when I use validationContext.MemberName, I am failing. I solved the problem with a temp fix by making it static as "term" but it is not a fix at all.

So, what is the way of retrieving property name from validationContext?

1

There are 1 best solutions below

6
On

Does validationContext.DisplayName do the trick?

You could then reflect to get the MemberName

var displayName = validationContext.DisplayName;

var memberName = validationContext.ObjectType.GetProperties()
    .Where(p => p.GetCustomAttributes(false).OfType<DisplayAttribute>().Any(a => a.Name == displayName))
    .Select(p => p.Name)
    .FirstOrDefault();

Possibly?