Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toast notifications in ASP.NET MVC 4

I want to display notifications whenever a user click on the "Add to Cart" button using the Toastr plugin. Basically, when a user click on the button, it executes the action "AddToCart" then redirects to the index page. When the page shows up, it checks the TempData value, then shows the notification.

This is the controller:

public ActionResult AddToCart(int id)
    {


        TempData["message"] = "Added";
        return RedirectToAction("Index");
    }

and the view:

@if (TempData["message"] != null)
{

    <script type="text/javascript">
        $(document).ready(function () {   
            toastr.success('Added')
        })
    </script>                                 
}

Update it worked according to @Exception's answer. However, if I use ajax such as:

@Ajax.ActionLink("Add to cart", "AddToCart", "Home", new { id = item.ProductId }, new AjaxOptions { UpdateTargetId="abc"})

it doesnt work. That may be because of the line:

$(document).ready(function ()

as the page is not reloaded. How can I fix it?

But this doesnt work. Please help. Thanks in advance!

like image 805
Tung Pham Avatar asked Aug 14 '14 05:08

Tung Pham


2 Answers

Answer 1:

<script type="text/javascript">
    $(document).ready(function () { 
       if('@TempData["message"]' == "Added"){
          toastr.success('Added');
       }
       else{ }
    });
</script> 

Answer 2:

Although TempData retain its value on one redirect but sometimes it creates problem(and it is recommended to avoid using TempData) in that case you can do as:

public ActionResult AddToCart(int id)
{
    .........
    return RedirectToAction("Index", new { message="Added" });  //Send Object Route//
}

public ActionResult Index(string message)
{
    .........
    if(!string.IsNullOrEmpty(message)) {
       Viewbag.message=message;
    }
    return View();
}

<script type="text/javascript">
    $(document).ready(function () { 
       if('@Viewbag.message' == "Added") {
          toastr.success('Added');
       }
       else{ }
    });
</script>
like image 156
Kartikeya Khosla Avatar answered Sep 18 '22 07:09

Kartikeya Khosla


Controller

TempData["message"] = "Added";

View

    @section scripts
{
        <script >
            $(document).ready(function () {
                if ('@TempData["message"]' == "Added") {
                    toastr.success('Action successfully changed....', 'ActionName');
                }
                else { }
            });
    </script>
}
like image 35
Alaa Hamdy Avatar answered Sep 21 '22 07:09

Alaa Hamdy