Tuesday, March 5, 2019

Passing data from Controller to View Examples

In the previous post we saw different ways in which we can pass data / objects from the controller to the View. In this post we will see a simple example on how to assign values in the controller and use them in the View using the different methods ViewData, ViewBag and TempData.

In the controller, we assign string and objects to the ViewData, ViewBag and TempData as follows.
        public IActionResult ControllerToView()
        {
            Employee objEmployee = new Employee();
            objEmployee.Name = "John";
            objEmployee.Age = 35;
            //
            ViewData["HelloViewData"] = "Hello from ViewData";
            ViewData["ViewDataObject"] = objEmployee;
            //
            ViewBag.HelloViewBag = "Hello from ViewBag";
            ViewBag.Employee = objEmployee;
            //
            TempData["HelloTempData"] = "Hello from TempData";
            return View();
        }

Once we set the values we can use them in the View as follows.

        @{
            var employee = ViewData["ViewDataObject"] as Employee;
        }
        <h6><u>ViewData - String</u></h6>
        @ViewData["HelloViewData"] <br /><br />
        <h6><u>ViewData - Object</u></h6>
        @employee.Name | @employee.Age  <br />
        <hr color="blue" />
        <h6><u>ViewBag - String</u></h6>
        @ViewBag.HelloViewBag <br /><br />
        <h6><u>ViewBag - Object</u></h6>
        @ViewBag.Employee.Name | @ViewBag.Employee.Age  <br />
        <hr color="blue" />
        <h6><u>TempData - String</u></h6>
        @TempData["HelloTempData"] <br /><br />

The output will be as follows.




Search Flipkart Products:
Flipkart.com

No comments: