Sunday, 23 December 2018

How to pass data from Controller to View / ViewBag and ViewData

ViewBag & ViewData is used to pass data from the controller to the view. We can also use strongly typed views to pass data from the controller to the view as well.

ViewBag: ViewBag uses the dynamic feature to store data and internally it is stored as name/value pairs.

Storing Data in ViewBag:

ViewBag.EmployeeId= "E001";

Retrieving Data from ViewBag:

string strEmpData = ViewBag.EmployeeId;

ViewData: ViewData is a dictionary of objects where data stored as string/value pair.

Storing Data in ViewData:
ViewData["EmployeeId"] = "E002";

Retrieving Data from ViewData:
string strEmpData = ViewData["EmployeeId"].ToString();

Both ViewBag and ViewData does not provide compile time error checking. If any error occurred can only found at runtime which is really very bad. To avoid this we can use strongly typed views to pass data from Controller to View.

No comments:

Post a Comment