In this article I will explain with an example, how to read (get) value of ViewData using JavaScript in ASP.Net MVC Razor.
The value of the ViewData will be read using Razor Syntax in JavaScript and the value will be displayed in JavaScript Alert Message Box.
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 ViewData object named “Message”.
Finally, the View is returned.
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public ActionResult Index(string name)
    {
        ViewData["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 ViewData 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 (ViewData["Message"] != null)
    {
        <script type="text/javascript">
            window.onload = function () {
                var message = '@ViewData["Message"]';
                alert(message);
            };
        </script>
    }
</body>
</html>
 
 
Screenshot
Read (Get) value of ViewData using JavaScript in ASP.Net MVC
 
 
Downloads