Tuesday, March 5, 2019

Passing data from Controller to View

There are different ways to pass values / objects from a controller to a view in Asp.Net Core MVC. Following are some of the commonly used ways.

ViewData – Returns a ViewDataDictionary, allows us to store key-value pairs in the controller and access them in the view. The key is a case sensitive string and the value can be any type int/string/object etc. When we use ViewData to pass custom objects we need to cast them in the View before using the properties.

ViewData properties are assigned in the controller as follows.
     ViewData["HelloViewData"] = "Hello from ViewData";

And used in the View layer as follows.
     @ViewData["HelloViewData"]

ViewBag – ViewBag is a wrapper around ViewData, it allows us to pass objects to the View and use them without having to cast it. ViewBag uses the dynamic feature of C# 4.0 to use objects directly.

ViewBag properties are assigned in the controller as follows.
     ViewBag.HelloViewBag = "Hello from ViewBag";

And used in the View layer as follows.
     @ViewBag.HelloViewBag

TempData – TempData is similar to ViewData but is ment to be used for short lived instances, values assigned to the TempData are available only in the current and subsequest requests. TempData can be used for features like assigning error messages in the controller and displaying them in the View.

TempData properties are assigned in the controller as follows.
     TempData["HelloTempData"] = "Hello from TempData";

And used in the View layer as follows.
     @TempData["HelloTempData"]


Search Flipkart Products:
Flipkart.com

No comments: