ASP.NET MVC 3 Remote Validation

后端 未结 2 901
野的像风
野的像风 2020-12-28 18:29

I have a validation controller within the route of my project that I\'m trying to use from within an area using the following attribute on the model\'s property...



        
相关标签:
2条回答
  • 2020-12-28 18:55

    Unfortunately that's how this attribute is implemented. Here's an excerpt from the constructor of this attribute:

    public RemoteAttribute(string action, string controller, string areaName) : this()
    {
        if (string.IsNullOrWhiteSpace(action))
        {
            throw new ArgumentException(MvcResources.Common_NullOrEmpty, "action");
        }
        if (string.IsNullOrWhiteSpace(controller))
        {
            throw new ArgumentException(MvcResources.Common_NullOrEmpty, "controller");
        }
        this.RouteData["controller"] = controller;
        this.RouteData["action"] = action;
        if (!string.IsNullOrWhiteSpace(areaName))
        {
            this.RouteData["area"] = areaName;
        }
    }
    

    Notice the IsNullOrWhiteSpace test against the areaName at the end that's killing everything?

    You could fix it by writing a custom remote attribute:

    public class MyRemoteAttribute : RemoteAttribute
    {
        public MyRemoteAttribute(string action, string controller, string area)
            : base(action, controller, area)
        {
            this.RouteData["area"] = area;
        }
    }
    

    and then:

    [MyRemote("IsValidUserName", "Validation", "", ErrorMessage = "Invalid username")]
    public string Username { get; set; }
    

    Now the proper data-val-remote-url="/Validation/IsValidUserName" will be generated.

    0 讨论(0)
  • 2020-12-28 19:03

    I came upon this same issue and found a solution that works for me. The remote attribute takes an AreaReference Enum.

    System.Web.Mvc.AreaReference is an ENUM which has two values UseRoot & UseCurrent more details found here

    Example useage that works for me:

    [Remote("IsValidUserName", "Validation", System.Web.Mvc.AreaReference.UseRoot, ErrorMessage = "Invalid username")]
    
    0 讨论(0)
提交回复
热议问题