Custom remote validation attribute throwing error

2019-06-09 15:15发布

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. Please see my code below.

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

enter image description here

enter image description here

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

0条回答
登录 后发表回答