In this article I will explain with an example, how to access value of ViewBag object inside JavaScript function in ASP.Net MVC Razor.
The ViewBag object value will be set inside Controller and then the value of the ViewBag object will be accessed inside JavaScript function using Razor syntax in ASP.Net MVC Razor.
 
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 two 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.
The 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.
The 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
Access ViewBag value inside JavaScript function in ASP.Net MVC
 
 
Downloads