Toast notifications in ASP.NET MVC 4
I want to show notifications when the user clicks the Add to Cart button using the Toastr plugin. Basically, when the user clicks the button, they perform the "AddToCart" action and then they are redirected to the index page. When the page is rendered, it checks the TempData value and then displays a notification.
This is the controller:
public ActionResult AddToCart(int id)
{
TempData["message"] = "Added";
return RedirectToAction("Index");
}
and view:
@if (TempData["message"] != null)
{
<script type="text/javascript">
$(document).ready(function () {
toastr.success('Added')
})
</script>
}
Update it worked as per @Exception answer. However, if I use ajax like:
@Ajax.ActionLink("Add to cart", "AddToCart", "Home", new { id = item.ProductId }, new AjaxOptions { UpdateTargetId="abc"})
he does not work. It could be because of the line:
$(document).ready(function ()
as the page doesn't reload. How can I fix this?
But it doesn't work. Please help. Thanks in advance!
source to share
Answer 1:
<script type="text/javascript">
$(document).ready(function () {
if('@TempData["message"]' == "Added"){
toastr.success('Added');
}
else{ }
});
</script>
Answer 2:
Although it TempData
retains its value in one redirect, but sometimes creates a problem (and it is recommended to avoid using it TempData
), in which case you can do this:
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>
source to share
Try adding a ViewBag statement to the Index Method that contains the TempData variable:
....
ViewBag.message = TempData["message"];
....
return View();
Index.cshtml:
@if (ViewBag.message != null)
{
<script type="text/javascript">
$(document).ready(function () {
toastr.success('Added')
})
</script>
}
source to share
This link might help: https://github.com/fatihBulbul/toastr.Net
Server side:
public ActionResult Index()
{
ViewBag.Message = Notification.Show("Hello World", position: Position.BottomCenter, type: ToastType.Error, timeOut: 7000);
return View();
}
Client side:
<script src="//code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css" rel="stylesheet" />
@Html.Raw(ViewBag.Message)
source to share