DEV Community

Azizul Arif
Azizul Arif

Posted on

Implementing Toastr Notifications in ASP.NET MVC: A Step-by-Step Guide for Enhanced User Experience"

Toastr is a simple yet powerful JavaScript library for displaying notifications to users. In this guide, I'll walk you through how to integrate Toastr into your ASP.NET MVC application, leveraging TempData to show success or error messages based on actions in your controller.

Step 1: Install Toastr

First, you'll need to add Toastr to your project. You can do this by including the Toastr CDN in your view files. Alternatively, you can download the Toastr files and include them in your project.

For this example, we'll use the CDN:

<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js" integrity="sha512-VEd+nq25CkR676O+pLBnDW09R7VQX9Mdiij052gVCp5yVH3jGtH70Ho/UUv4mJDsEdTvqRCFZg0NKGiojGnUCw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css" rel="stylesheet" />
Enter fullscreen mode Exit fullscreen mode

Step 2: Create the Notification Partial View

Next, create a partial view _Notification.cshtml that will handle the Toastr notifications. This partial view will check if there are any messages in TempData and display them accordingly.

@if (TempData["error"] is not null)
{
    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js" integrity="sha512-VEd+nq25CkR676O+pLBnDW09R7VQX9Mdiij052gVCp5yVH3jGtH70Ho/UUv4mJDsEdTvqRCFZg0NKGiojGnUCw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

    <script type="text/javascript">
        toastr.error('@TempData["error"]');
    </script>
}


@if (TempData["success"] is not null)
{
    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js" integrity="sha512-VEd+nq25CkR676O+pLBnDW09R7VQX9Mdiij052gVCp5yVH3jGtH70Ho/UUv4mJDsEdTvqRCFZg0NKGiojGnUCw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

    <script type="text/javascript">
        toastr.success('@TempData["success"]');
    </script>
}

Enter fullscreen mode Exit fullscreen mode

Step 3: Include the Partial View in Your Layout

To ensure that the notifications are displayed on every page where they might be needed, include the _Notification partial view in your main layout file (_Layout.cshtml).

<div class="container">
    <main role="main" class="pb-3">
        <partial name="_Notification" />
        @RenderBody()
    </main>
</div>
Enter fullscreen mode Exit fullscreen mode

Step 4: Update Your Controller

Now, update your controller to set TempData values for success or error messages. Here's an example using a VillaController:

public class VillaController : Controller
{
    private readonly ApplicationDbContext _db;

    public VillaController(ApplicationDbContext db)
    {
        _db = db;
    }

    public IActionResult Create()
    {
        return View();
    }

    [HttpPost]
    public IActionResult Create(Villa obj)
    {
        if (ModelState.IsValid)
        {
            _db.Villas.Add(obj);
            _db.SaveChanges();
            TempData["success"] = "The villa has been created successfully";
            return RedirectToAction("Index");
        }

        TempData["error"] = "The villa could not be created";
        return View(obj);
    }

    public IActionResult Update(int villaId)
    {
        Villa? obj = _db.Villas.FirstOrDefault(m => m.Id == villaId);
        if (obj is null)
        {
            return RedirectToAction("Error", "Home");
        }
        return View(obj);
    }

    [HttpPost]
    public IActionResult Update(Villa obj)
    {
        if (ModelState.IsValid && obj.Id > 0)
        {
            _db.Villas.Update(obj);
            _db.SaveChanges();
            TempData["success"] = "The villa has been updated successfully";
            return RedirectToAction("Index");
        }

        TempData["error"] = "The villa could not be updated";
        return View(obj);
    }

    public IActionResult Delete(int villaId)
    {
        Villa? villa = _db.Villas.FirstOrDefault(v => v.Id == villaId);
        if (villa is null)
        {
            return RedirectToAction("Index");
        }
        return View(villa);
    }

    [HttpPost]
    public IActionResult Delete(Villa obj)
    {
        Villa? villa = _db.Villas.FirstOrDefault(m => m.Id == obj.Id);
        if (villa is not null)
        {
            _db.Villas.Remove(villa);
            _db.SaveChanges();
            TempData["success"] = "The Villa has been deleted successfully";
            return RedirectToAction("Index");
        }

        TempData["error"] = "Villa could not be deleted";
        return View(villa);
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Test Your Toastr Notifications

Run your application and perform actions like creating, updating, or deleting a Villa. You should see the Toastr notifications appear as intended based on the result of the operation.

Top comments (0)