Thursday 22 February 2018

Access ViewBag value inside JavaScript function in ASP.Net MVC

Access ViewBag value inside JavaScript function in ASP.Net MVC

Description:
In this example we explain that how to use ViewBag value inside JavaScript function in Asp.Net MVC.or how to access ViewBag value in JavaScript function using MVC Razor View. Or how to access ViewBag value at client side in ASP.Net MVC.or how to transfer ViewBag value from controller to Razor view in MVC.

Controller:

public class EmployeeController : 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:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <title>Access ViewBag value inside JavaScript function in ASP.Net MVC</title>
</head>
<body>
    @using (Html.BeginForm("Index", "Employee", FormMethod.Post))
    {
        <input type="text" id="txtEmpName" name="name"/>
        <input type="submit" id="btnSubmit" value="Get Local Time"/>
    }
    @if (ViewBag.Message != null)
    {
        <script type="text/javascript">
            window.onload = function () {
                alert("@ViewBag.Message");
            };
        </script>
    }
</body>
</html>


0 comments:

Post a Comment