Skip to content
Advertisement

Show notification after redirecting to page in ASP .NET MVC

Below is my ajax code:

$.ajax({
         url: '@Url.Action("AddUser", "ControllerName")',
         dataType: 'json',
         contentType: 'application/x-www-form-urlencoded; charset=utf-8',
         type: 'POST',
         data: {
                //data
         },
         success: function (data, textStatus, jqXHR) {
               console.log(jqXHR.status);
               if (data.isSuccess) {
                   alert(data.message);
               }
               else {
                   alert(data.message);
               }
               window.location.href = "@Url.Action("Index", "ControllerName")";
         },
         error: function (jqXHR, textStatus, errorThrown) {
               console.log(jqXHR.status);
               window.location.href = "@Url.Action("Index", "ControllerName")";

         }
});

Instead of showing alert(data.message); I want to show custom notification after page load.

I don’t want to pass any query string parameters as it is visible in the url.

There are two possible ways to show notifications:

1)

$(".notificationdiv").html("<div class='notification  alert alert-success' role='alert'>
<strong> Operation performed successfully</strong>
</div>");
$(".notification").fadeOut(4000);
  1. I have a custom Base Controller virtual method to show notifications. Calling that method after page redirection.

Please let me know how to show notifications. Code sample is appreciated. Thanking you in advance.

Advertisement

Answer

Use sessionStorage

In ajax success before window.location.href add this

sessionStorage.successMessage= true;

And add this in your jquery

$(function () {
    if (sessionStorage.successMessage) {
        $(".notificationdiv").html("<div class='notification  alert alert-success' role='alert'><strong> Operation performed successfully</strong></div>");
        $(".notification").fadeOut(4000);
        sessionStorage.successMessage= false;
        sessionStorage.removeItem("successMessage") //if you want remove from session storage
    }
});
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement