Alert Message From Controller View Using JavaScript Alert MessageBox

Overview

In this blog, I will explain with an example, how to display a message from Controller in View, using JavaScript alert MessageBox.

The message sent from Controller to View will be displayed in JavaScript Alert MessageBox using ViewBag Object object.
Controller

First, we create new project, using Visual Studio. Choose Project template MVC. Now, we create Controller. Controller has two action methods, which are mentioned below.
  • Action method for handling GET operation.
    Inside this Action method, simply the view is returned.

  • Action method for handling POST operation.
    This Action method handles the form submission and it accepts the value of the form element as a parameter.
The name value fetched from the Form collection and the current Server date and time is set to a ViewBag object named “Message”.
Controller Code
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. namespace AlertMessge.Controllers
  7. {
  8. public class HomeController : Controller
  9. {
  10. public ActionResult Index()
  11. {
  12. return View();
  13. }
  14. [HttpPost]
  15. public ActionResult Index(string name)
  16. {
  17. ViewBag.Message = String.Format("Hello{0}.\\ncurrent Date and time:{1}", name, DateTime.Now.ToString());
  18. return View();
  19. }
  20. }
  21. }
VIEW
The View consists of HTML form, which has been created, using the Html.BeginForm method with the parameters, mentioned below.
  • ActionName
    Name of the Action. In this case, the name is Index.

  • ControllerName
    Name of the Controller. In this case, the name is Home.

  • FormMethod
    It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The Form consists of two elements i.e. a TextBox and a Submit Button.
The ViewBag object named Message is checked for NULL and if it is not NULL, the value of the object is displayed, using JavaScript alert MessageBox.
View Code
  1. @{
  2. Layout = null;
  3. }
  4. <!DOCTYPE html>
  5. <html>
  6. <head>
  7. <meta name="viewport" content="width=device-width"/>
  8. <title>Index</title>
  9. </head>
  10. <body>
  11. @using (Html.BeginForm("Index", "Home", FormMethod.Post))
  12. {
  13. <input type="text" id="txtName" name="name"/>
  14. <input type="submit" id="btnSubmit" value="Get Current Time"/>
  15. }
  16. @if (ViewBag.Message != null)
  17. {
  18. <script type="text/javascript">
  19. window.onload = function () {
  20. alert("@ViewBag.Message");
  21. };
  22. </script>
  23. }
  24. </body>
  25. </html>
Output


Summary

In this section, I explained about the message sent from Controller to View, which will be displayed In JavaScript alert MesssageBox, using ViewBag object.