How to keep Toastr Notification alive after redirection to another page in ASP MVC

回眸只為那壹抹淺笑 提交于 2019-12-06 21:10:42

If you want to pass one-time message from an action method to another action method, you will need to use 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 then retrieve it at the next page either inside action method or view. Please note that it would be cleared out at the end of the request after you read it.

Profil.cshtml

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

Update

Above code works. If you use default ASP.NET MVC Layout, please make sure you place the script inside Scripts section, so that it renders 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 you use toastr in other places, you might want to consider bundle and minfy them with other scripts and styles.

If you don't need to redirect to "Profil", then I agree you could use Ajax and on the success callback you could show your toastr. If you need to redirect then you can set the ViewBag.Message as you do and then do something like

@if (ViewBag.Message != null)
{
<script type="text/javascript">toastr.success("@ViewBag.Message");</script>
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!