In this article I will explain with an example, how to display 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.
Note: For beginners in ASP.Net MVC, please refer my article ASP.Net MVC Hello World Tutorial with Sample Program example.
 
 

Controller

The Controller consists of following Action methods.

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 parameter.
Note: The name of the parameter must be same as the value of name attribute specified for the Form element.
 
Finally, name value fetched from the Form collection and the Current Server Date and Time is set to a ViewBag object named “Message”.
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public ActionResult Index(string name)
    {
        ViewBag.Message = string.Format("Hello {0}.\\nCurrent Date and Time: {1}", name, DateTime.Now.ToString());
        return View();
    }
}
 
 

View

The View consists of an HTML Form which has been created using the Html.BeginForm method with the following parameters.
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.
Finally, ViewBag object named Message is checked for NULL and if it is not NULL then the value of the object is displayed using JavaScript Alert MessageBox.
@{
     Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
        <input type="text" id="txtName" name="name" />
        <input type="submit" id="btnSubmit" value="Get Current Time" />
    }
    @if (ViewBag.Message != null)
    {
        <script type="text/javascript">
            window.onload = function () {
                alert("@ViewBag.Message");
            };
        </script>
    }
 
</body>
</html>
 
 

Screenshot

ASP.Net MVC: Display Message from Controller in View using JavaScript Alert MessageBox
 
 

Downloads