asp.net-mvc-3modelcontrolleractionremote-validation

How to handle Remote Attributes on Model Edit? ASP.Net MVC3


I'm using Remote Attribute in my Model to check duplicate Page Titles as follows

public class Page
{
  [Remote("CheckDuplicate", "Page", ErrorMessage = "Title already taken")]
  public string Title { get; set; }
}

And In controller, I'm returning JsonResult data based on "Check" result as follows:

public JsonResult CheckDuplicate(string Title)
{
   var result = db.Pages.Where(a => a.Title == Title).Count() == 0;
   return Json(result, JsonRequestBehavior.AllowGet);
}

This is working fine in Create action, But problem is, It's restricting me to Edit the Existing page, Since It's checking the same query.

How to solve this Problem? Please Suggest me something


Solution

  • Your question looks similar to this: ASP.NET MVC 3 Remote validation to allow original value

    I think the trick is to use the AdditionalFields argument to your remote validation attribute in your model and combine that with a hidden field in your view - like suggested in the above StackOverflow post. Then you can send in the "initial" value along with the new value to your remote validation method and use both arguments to do your uniqueness check.

    Another example of how to fix this can be found here: https://stackoverflow.com/a/4756796/700926

    The documentation for AdditionalFields can be found here: http://msdn.microsoft.com/en-us/library/system.web.mvc.remoteattribute.additionalfields(v=vs.98).aspx