Tips for Maintaining Toastr Notifications on ASP MVC Even After Redirecting to Another Page

I am currently working on an ASP MVC 5 application and encountering an issue with displaying a Toast notification.

The toast notification is supposed to appear after updating a user's information to confirm the success of the operation.

However, it disappears quickly (in just 2 seconds) after the next page loads. I suspect this is because of using server-side code (C# in this case), which causes the entire page, including the JavaScript files, to reload and thus the toastr disappears.

Is there a way to make it stay visible for a little longer?

I attempted to pass the necessary information to the next page so that it would display the toastr instead of the current page, but that didn't work.

Here is a snippet of the code:

View:

 @using (Html.BeginForm("Edit", "Client", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
    {
        <input type="submit" value="Save" class="btn btn-default" onclick="Update()">
    }

        <script src="/template/web/js/jquery-2.2.3.min.js"></script>
        <script src="~/Scripts/toastr.js"></script>
        <script>

            function Update() {
                toastr.success("Your information has been updated successfully!");
            }
        </script>

Controller:

[HttpPost]
    public ActionResult Edit(int id, Client cmodel)
    {
        try
        {

                ClientManagement cdb = new ClientManagement();
            if (cdb.UpdateDetails(cmodel))
            {
                ViewBag.Message = "Client Details Edited Successfully";
            }

            return RedirectToAction("Profile");
        }
        catch
        {
           return View();
        }
    }

Profile:

 public ActionResult Profile()
    {
        ClientManagement dbhandle = new ClientManagement();
        ViewBag.Message = TempData["Message"];
        return View(dbhandle.GetClientsInfo());
    }

In the Profile View (bottom of the page):

<link href="~/Content/toastr.min.css" rel="stylesheet" />
script src="~/scripts/toastr.js"></script>
        <script src="~/scripts/toastr.min.js"></script>

     @if (ViewBag.Message != null)
    {
        <script type="text/javascript">toastr.success("@ViewBag.Message");</script>
    }

Answer №1

In order to transfer a one-time message from one action method to another, utilize TempData.

[HttpPost]
public ActionResult Edit(int id, Client cmodel)
{
   try
   {
      ClientManagement cdb = new ClientManagement();
      if (cdb.UpdateDetails(cmodel))
      {
         TempData["Message"] = "Client Details Edited Successfully";
      }
      return RedirectToAction("Profil");
   }
   catch
   {
      return View(cmodel);
   }
}

You can then access the message on the following page either within the action method or view. Remember that it will be cleared at the end of the request once read.

Profil.cshtml

@if (TempData["Message"] != null)
{
   <script type="text/javascript">toastr.success("@TempData["Message"]");</script>
}

Update

https://i.sstatic.net/HXbqu.png

The above code is effective. When using the default ASP.NET MVC Layout, ensure to place the script within the Scripts section to ensure it loads after jQuery.

@section Scripts {
    <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css" rel="stylesheet" />
    @if (TempData["Message"] != null)
    {
        <script type="text/javascript">toastr.success("@TempData["Message"]");</script>
    }
}

FYI: If using toastr in multiple locations, consider bundling and minifying them with other scripts and styles.

Answer №2

If there's no need to redirect to the "Profile" page, you could opt for using Ajax. In the success callback, you can display your toastr message. However, if redirection is required, you can set the ViewBag.Message as you already do, and then implement something like this:

@if (ViewBag.Message != null)
{
<script type="text/javascript">toastr.success("@ViewBag.Message");</script>
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Presenting a trio of distinct tables each accompanied by its own unique button option

I am attempting to create a functionality where there are 3 buttons and when a user clicks on one of them, it shows the corresponding table while hiding the other two. I have experimented with using getElementById to manipulate the display property of the ...

Using querySelector() to target specific divs by their classes while excluding any other classes

I am attempting to retrieve only the first divs while excluding the second ones: <div class="_5pcr userContentWrapper"> <div class="_5pcr userContentWrapper _4nef"> After researching, I discovered that the querySelector function should be abl ...

Inconsistencies in JavaScript comparison across various web browsers

Here is a snippet from my JavaScript code var dataList = eval(strArray[0]); for (i = 0; i < dataList.length; i++) { console.log(((dataList[i].isFollowed == 0) ? "Follow" : "Unfollow")); } However, this code exhibits varying behavio ...

What is the best way to set a specific image as the initial image when loading 'SpriteSpin'?

I'm currently working on creating a 360-degree view using the SpriteSpin API. Everything is functioning as expected, but I have an additional request. I need to specify a specific image to be the initial landing image when the page loads. The landing ...

Why doesn't the browser redirect even though Fiddler is indicating otherwise?

The 'Execute' function is triggered by XmlHttpRequest. $.ajax( { async: false, url: 'Task/Execute/1' }); The 'Execute' function initiates a redirect ...

Avoiding a constantly repeating video to prevent the browser from running out of memory

Using HTML5, I created a video that loops and draws the frames to canvas. I decided to create multiple canvases and draw different parts of the video on each one. However, after some time, I encountered an issue where Google Chrome would run out of memory. ...

What is the process for including a scope in an Angular.js HTTP controller?

I am looking to access a $scope variable within this controller in order to utilize Angular functions like ng-click and ng-change in my HTML. Currently, I am only able to use the $http function but unable to execute any Angular methods on it. I am struggli ...

Tips for choosing a specific cell in a table

I currently have a total of 14 cells that have been generated. Is there a way for me to individually select and manipulate a specific cell out of the 14? I am looking to make only one cell unique, while leaving the rest to be displayed as they are in the ...

What is the best way to upload a file using AJAX request in Sinatra?

I am attempting to upload a file using a jQuery AJAX function with a Ruby-Sinatra function. Here is the code snippet: <form id="ucform" method="post" action="#" enctype="multipart/form-data"> <input type="file" id="cfile" name="cfile" onchange= ...

What is the best way to incorporate multiple conditions within a React component?

When working in React, I have the ability to conditionally render any div using the following code snippet: {hasContent && <span>{value}</span> } Recently, I attempted to include two conditions as follows: {hasContent || hasDesc &am ...

What could be causing the state to not update as anticipated?

I am currently in the process of developing a TicTacToe game and have a requirement to maintain the current player in state under the name currentPlayer. The idea is that after one player makes a move, I need to update currentPlayer to represent the opposi ...

Circular dependency situation encountered in Angular 2 shared module

I'm currently working on a share module setup that is structured as follows: @NgModule({ exports: [ CommonModule, HttpModule, OneModule, TwoModule ] }) export class SharedModule { } The OneModule imports the SharedModule in order ...

Explore the wonders of Jest and Playwright by heading over to youtube.com and discovering an exciting video!

As part of my job responsibilities, I have been tasked with automating tests for a web application that our team developed. Using Playwright and Jest, I am required to write automation scripts from scratch. To practice utilizing Playwright, I decided to cr ...

"Utilize the on() method to bind a click event to dynamically generated elements received

After reading several discussions on using on() to link events to dynamically generated HTML elements, I decided to create an example (FIDDLE) where the click event is bound to elements div.clicktitle fetched via AJAX. These div elements contain data attri ...

Is there a way to automatically hide divs with the style "visibility:hidden" if they are not visible within the viewport?

Currently, I am working on developing a mobile web app. Unfortunately, Safari in iOS 5.1 or earlier has limited memory capabilities. In order to reduce memory usage while using css3 transitions, I have discovered that utilizing the css styles "display:none ...

Encountering a Typescript TypeError in es2022 that is not present in es2021

I'm attempting to switch the target property in the tsconfig.json file from es2015 to es2022, but I am encountering an error while running tests that seem to only use tsc without babel: Chrome Headless 110.0.5481.177 (Mac OS 10.15.7) TypeError: Can ...

Is CurrentThread.CurrentCulture disregarded by JavaScriptSerializer in ASP.net MVC?

I am currently investigating whether the JavaScriptSerializer used internally to serialize data to JSON in ASP.net MVC 4 ignores the CultureInfo of the current thread. Here are my observations so far. I have set the culture info properties in the Applica ...

Firestore Query sends data object to browser

When making a Firestore query, the browser is displaying [object Object],[object Object] instead of the expected output: router.get('/jobopportunities', async(req, res) => { var jobArray = []; const snapshot = await fireba ...

Is there a way to download and store the PDF file created using html2pdf in Node.js on my local machine?

I have successfully generated a PDF using html2pdf, but now I want to either send it to my server in Node.js or save it directly onto the server. Currently, the PDF is downloaded at the client's specified path, but I also need a copy saved on my serve ...

React useEffect appended script not activating

I'm having trouble loading a script that should generate an iframe and display a weather widget upon trigger. I am able to append the script correctly, but it doesn't seem to be called and does not create the iframe. Even when I directly add the ...