Data Passing Between Controller and View
Using Form Like POST Method
ViewBag.Number and (int)ViewData[“Number”] from controller to View
Controller to Controller TempData
| |
1. Using ViewData
ViewData is a dictionary-based way to pass data to the view. It uses the ViewDataDictionary class and is accessed by string keys.
Example:
Controller:
| |
View (Index.cshtml):
| |
2. Using ViewBag
ViewBag is a dynamic wrapper around ViewData. It allows you to set and retrieve data using dynamic properties. ViewBag uses the dynamic keyword, which provides a more flexible and convenient way to pass data.
Example:
Controller:
| |
View (Index.cshtml):
| |
Key Differences
Type:
ViewDatais a dictionary (ViewDataDictionary) and requires type casting when retrieving data.ViewBagis a dynamic object, which provides a more straightforward syntax.Using ViewData:
1 2string message = (string)ViewData["Message"]; DateTime date = (DateTime)ViewData["Date"];Using ViewBag:
1 2string message = ViewBag.Message; DateTime date = ViewBag.Date;Performance:
ViewBagcan be slightly less performant thanViewDatabecauseViewBagrelies on the dynamic type and runtime binding, whereasViewDatauses a strongly typed dictionary.Functionality: Both
ViewDataandViewBagare used for similar purposes, butViewBagoffers a more concise syntax due to its dynamic nature.
