Custom remote validation attribute throwing error at server side in ASP.NET MVC

五迷三道 提交于 2019-12-08 12:18:52

问题


I am developing an ASP.NET MVC Web Application. In my project I am doing remote validation using data annotation to my view model class. I know default remote attribute does not support server validation. I can validate it again in action method. But I do not want to do that it is violating separation of concerns. So I tried to create custom server client remote validation attribute. I found a code online and I used it. But it is giving me error when server validation is occurred.

This is my custom remote validation attribute:

public class RemoteClientServerAttribute : RemoteAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            // Get the controller using reflection
            Type controller = Assembly.GetExecutingAssembly().GetTypes()
                .FirstOrDefault(type => type.Name.ToLower() == string.Format("{0}Controller",
                    this.RouteData["controller"].ToString()).ToLower());
            if (controller != null)
            {
                // Get the action method that has validation logic
                MethodInfo action = controller.GetMethods()
                    .FirstOrDefault(method => method.Name.ToLower() ==
                        this.RouteData["action"].ToString().ToLower());
                if (action != null)
                {
                    // Create an instance of the controller class
                    object instance = Activator.CreateInstance(controller);
                    // Invoke the action method that has validation logic
                    object response = action.Invoke(instance, new object[] { value });
                    if (response is JsonResult)
                    {
                        object jsonData = ((JsonResult)response).Data;
                        if (jsonData is bool)
                        {
                            return (bool)jsonData ? ValidationResult.Success :
                                new ValidationResult(this.ErrorMessage);
                        }
                    }
                }
            }

            return ValidationResult.Success;
            // If you want the validation to fail, create an instance of ValidationResult
            // return new ValidationResult(base.ErrorMessageString);
        }

        public RemoteClientServerAttribute(string routeName)
            : base(routeName)
        {
        }

        public RemoteClientServerAttribute(string action, string controller)
            : base(action, controller)
        {
        }

        public RemoteClientServerAttribute(string action, string controller,
            string areaName)
            : base(action, controller, areaName)
        {
        }
    }

This is my model:

public class CreateCategoryVM
    {
        [Required]
        [MaxLength(50)]
        [RemoteClientServer("IsNameUnique","Category",ErrorMessage="Name is already taken")]
        public string Name { get; set; }
    }

I tried this also adding area name:

[RemoteClientServer("IsNameUnique","Category","Admin",ErrorMessage="Name is already taken")]
            public string Name { get; set; }

This is my remote validation action method:

public JsonResult IsNameUnique(string Name)
            {
                IEnumerable<Category> categories = categoryRepo.Categories.Where(x => x.Name.Trim() == Name);

            Category category = categories.FirstOrDefault();
            return Json(category==null, JsonRequestBehavior.AllowGet);
        }

But when I run the code an create, client validation is working properly if the name is already taken. But when I create with different name that does not exist yet, it is giving me error at server-side.

These are the screenshots error:

Why is that error throwing? My controller is in new area created. Is this dealing with that?

来源:https://stackoverflow.com/questions/37939976/custom-remote-validation-attribute-throwing-error-at-server-side-in-asp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!