Show javascript alert message from .net mvc controller to view

In a .NET MVC application, it's common to show alert messages to the user based on certain actions or events that occur in the application. One way to achieve this is by using JavaScript alert messages.

In this blog post, we will go through the steps to show a JavaScript alert message from a .NET MVC controller to the view using a code example.

Step 1: Create a new MVC application To start, create a new MVC application in Visual Studio. You can do this by selecting "File" -> "New" -> "Project" -> "Web" -> "ASP.NET Web Application". Choose the "MVC" template and click "OK" to create the application.

Step 2: Create a controller action Next, create a controller action that will trigger the alert message. For example, you can create an action that checks if a user is logged in and displays a message if they are not. Here's an example:
public ActionResult CheckLogin()
    if (!User.Identity.IsAuthenticated)
        ViewBag.Message = "You need to log in to access this page.";
        return View();
    return RedirectToAction("Index", "Home");
In this example, we check if the user is authenticated using the `User.Identity.IsAuthenticated` property. If the user is not authenticated, we set a message using the `ViewBag` object and return the view. If the user is authenticated, we redirect them to the "Index" action of the "Home" controller.

Step 3: Add the view Next, add a view for the "CheckLogin" action. In the view, we will use JavaScript to display the alert message. Here's an example:
    ViewBag.Title = "Check Login";


@if (ViewBag.Message != null) { }
In this example, we first display the message using the `ViewBag.Message` property. We then use JavaScript to check if the message has a length greater than zero, and if so, we display it using the `alert` function.

Step 4: Test the application Finally, run the application and navigate to the "CheckLogin" action. If you are not logged in, you should see the alert message displayed. If you are logged in, you should be redirected to the "Index" action of the "Home" controller.


In this blog post, we have shown how to display a JavaScript alert message from a .NET MVC controller to the view using a code example. By following these steps, you can easily implement alert messages in your MVC application to improve the user experience.
Best quality Asp .Net Ajax Control Toolkit tutorials.

Give your valuable comments.

3 + 7 =

About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2024 CodingFusion
50+ C# Programs for beginners to practice