Skip to content

Instantly share code, notes, and snippets.

@ChrisMoney
Created February 11, 2025 14:21
Show Gist options
  • Save ChrisMoney/cac4efe2ed354907f0580f940d7d077f to your computer and use it in GitHub Desktop.
Save ChrisMoney/cac4efe2ed354907f0580f940d7d077f to your computer and use it in GitHub Desktop.
Call .NET MVC Core Controller from JS Ajax plus store and display success message after page reload
MVC-Razor AJAX
// AJAX calls .NET MVC Core Controller
// Stores success message and fetches it to display once page is updated
function confirmTransferAction(event) {
// console.log("@Url.Action("UpdateAccountEmail", "CustomerProfiles")");
var id = document.getElementById('adminId').value;
var email = document.getElementById('newEmail').value;
if (confirm("Are you sure you want to transfer the account?")) {
$.ajax({
url: "@Url.Action("UpdateAccountEmail", "CustomerProfiles")",
type: 'POST',
contentType: "application/json",
data: JSON.stringify({
id: id,
email: email
}),
success: function (response) {
console.log(response);
if (response.status === 'OK') {
sessionStorage.setItem("successMessage", "Account transfer successful!");
location.reload();
} else {
emailError.textContent = "User email already exists";
}
},
error: function (xhr, status, error) {
console.error('Error:', error);
alert('An error occurred while updating the email');
}
});
}
}
// get the success message that was cached in API call and display it
document.addEventListener("DOMContentLoaded", function () {
var successMessage = sessionStorage.getItem("successMessage");
if (successMessage) {
var messageDiv = document.getElementById("successMessage");
messageDiv.textContent = successMessage;
messageDiv.style.display = "block";
// Clear the message after displaying it
sessionStorage.removeItem("successMessage");
}
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment