In ASP.NET MVC, when using Ajax.BeginForm, client-side events like OnBegin,
OnSuccess, and OnFailure let you hook into the AJAX request lifecycle so you can run JavaScript at specific moments during the request.
These events are part of the AjaxOptions object and are triggered
automatically by the
jQuery Unobtrusive Ajax library.
AJAX Lifecycle Overview
OnBegin → before the request is sent
OnSuccess → when a successful response is received (HTTP 200 OK)
OnFailure → when the server returns an error (like 400/500), or AJAX fails
OnComplete → after the AJAX call is finished (success or failure)
1. OnBegin
OnBegin = "onFormBegin" // function name
Triggered before the form is submitted. You can use this to:
Show a loading spinner
Validate fields manually
Cancel submission by returning false
Example:
function onFormBegin() {
console.log("Form is about to be submitted...");
return true; // proceed
// return false; // cancel AJAX request
}
2. OnSuccess
OnSuccess = "onFormSuccess" // function name
Triggered when the server returns a successful response (200 OK). You can use this to:
Show a success message
Update the UI
Reset the form
Example:
function onFormSuccess(response) {
console.log("Form submitted successfully.");
$("#messageBox").text("Saved successfully!");
}
If the action returns HTML, it will also be inserted into the UpdateTargetId DOM element.
3. OnFailure
OnFailure = "onFormFailure" // function name
Triggered when:
The AJAX request fails (network/server issue)
The action returns a non-success status (like 500 Internal Server Error)
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
In ASP.NET MVC, when using Ajax.BeginForm, client-side events like
OnBegin,OnSuccess, andOnFailurelet you hook into the AJAX request lifecycle so you can run JavaScript at specific moments during the request.These events are part of the
AjaxOptionsobject and are triggered automatically by the jQuery Unobtrusive Ajax library.AJAX Lifecycle Overview
OnBegin→ before the request is sentOnSuccess→ when a successful response is received (HTTP 200 OK)OnFailure→ when the server returns an error (like 400/500), or AJAX failsOnComplete→ after the AJAX call is finished (success or failure)1. OnBegin
Triggered before the form is submitted.
You can use this to:
falseExample:
2. OnSuccess
Triggered when the server returns a successful response (200 OK).
You can use this to:
Example:
If the action returns HTML, it will also be inserted into the
UpdateTargetIdDOM element.3. OnFailure
Triggered when:
Example:
How to Wire These Up
Bonus: OnComplete
Not directly in
AjaxOptions, but you can hook into global AJAX events:Notes
"onFormSuccess") are just string names. Make sure those functions exist in JavaScript scope.data-ajax-*attributes are correctly output.