Reputation: 252
When returning from an AJAX query, is there a way to determine whether the server side validation added any errors?
I have tried
if ($('#MyForm').valid() == true)
...
in an OnSuccess
function, but it seems to always be true, regardless of whether the server side validation failed or not. The refreshed HTML if generates does put in the error as expected, so I know the validation is working correctly.
I suspect the valid()
method is just re-running the client-side validation.
Upvotes: 3
Views: 292
Reputation: 4701
Check out the technique in this tutorial. Validation is done server side using Data annotations. Using a custom filter, validation errors are sent to the client and on the client side, you call revalidate()
from the unbotrusive js
$.validator.unobtrusive.revalidate(form, validationResult);
Upvotes: 1
Reputation: 9271
If you run an ajax call to the server, you can simply compose the Json return.
Usually I wrap my responses in a class containing a property that tell me if all is ok, one that contain the data and one with the eventual error message.
public class MyJsonReposnse
{
public bool Valid {get;set;}
public string Error {get;set;}
public IList<MyClass> Data {get;set;}
}
Then from your controller you return the json and from your onSuccess
of the jQuery call, you check the value of Valid
and act accordingly
Upvotes: 2