MVC4 & IClientValidatable - Automatic AJAX calls to server side validation

前端 未结 1 1431
面向向阳花
面向向阳花 2021-01-20 13:01

I\'m looking to implement custom client side validation in MVC4. I currently have it working well with the standard attributes, such as this in my model

publ         


        
相关标签:
1条回答
  • 2021-01-20 14:02

    MVC comes with RemoteAttribute which internally makes an ajax call to a controller method that returns a Json value indicating if validation succeeded or failed

    public JsonResult IsValid(string SourceDirectory)
    {
      if (someCondition) //test if the value of SourceDirectory is valid
      {
        return Json(true, JsonRequestBehavior.AllowGet); // indicates its valid
      }
      else
      {
        return Json(false, JsonRequestBehavior.AllowGet); // indicates its not valid
        // or return Json("A custom error message that overrides the default message defined in the attribute");
      }
    }
    

    and decorate your property with

    [Remote("IsValid", "YourController", ErrorMessage = "The path is not valid")]
    public string SourceDirectory { get; set; }
    

    Note: The RemoteAttribute is only for client side (jquery unobtrusive validation) and you may still need additional server side validation.

    Refer How to: Implement Remote Validation in ASP.NET MVC for a detailed example

    0 讨论(0)
提交回复
热议问题