I have something like this:
I am using Ajax.BeginForm and its updatetargetid is 开发者_运维百科a div which basically informs user whether it was successfully submitted or not and the problem, if any. My controller function that is handling the form submission checks if there were any errors like duplicate entries and such and does re-checking of client-side rules and returns Content(....) accordingly.
This is what I'm using to clear form afterwards, but as you can see that the form would still get cleared even when my controller function has detected some problem that client-side didn't. I set AjaxOptions OnComplete = "onComplete"
.
function onComplete() {
if ($("#myForm").validate().form()) {
$("#myForm").clearForm();
}
}
Use function onComplete(ajaxContext){ } instead of function onComplete() {}
From the server end, if there are model validation errors, it usually means the validation summary (if supported) contains some error messages. Using ajaxContext, you can read the the response that is returned as part of ajax call and check the values of validation summary element.
Other option is to design a strategy between your controller and view - e.g. specify an error indicator as part of your response header and use this to decide whether to clear your form or not in OnComplete handler.
so then whats the problem? You simply dont call the onComplete function when there is a server side error. But instead display an error message to let the user know that nothing will happen as there was a server side error. And this way the form will not get cleared. If everything does work on the server side, then only then will you call the onComplete function.
PK
精彩评论