How Do we pass data from view to Controller
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:
ViewData
is a dictionary (ViewDataDictionary
) and requires type casting when retrieving data.ViewBag
is a dynamic object, which provides a more straightforward syntax.Using ViewData:
1 2
string message = (string)ViewData["Message"]; DateTime date = (DateTime)ViewData["Date"];
Using ViewBag:
1 2
string message = ViewBag.Message; DateTime date = ViewBag.Date;
Performance:
ViewBag
can be slightly less performant thanViewData
becauseViewBag
relies on the dynamic type and runtime binding, whereasViewData
uses a strongly typed dictionary.Functionality: Both
ViewData
andViewBag
are used for similar purposes, butViewBag
offers a more concise syntax due to its dynamic nature.