Asp.Net MVC Exploring Controllers in-depth Part 2.Best Dot Net Courses
Learn MVC to build web apps using the Model View Controller pattern. ASP.NET MVC 5 provides this functionality to the ASP.NET framework as an alternative to the Web Forms pattern
Passing data from Controller to View
ViewBag vs. ViewData vs. TempData
All three are properties
-
- ViewData is a dictionary object that you put data into, which then becomes available to the ViewData is a derivative of the ViewDataDictionary class, so you can access by the familiar “key/value” syntax.
- ViewBag object is a wrapper around the ViewData object that allows you to create dynamic properties for the ViewBag.
- Both the ViewData and ViewBag objects are great for accessing extra data (i.e., outside the data model), between the controller
-
Asp.Net MVC Exploring Controllers in-depth Part 2.Best Dot Net Courses
- TempData has an additional advantage of Passing data between the current and next HTTP requests.
1 2 3 4 5 6 7 8 |
public ViewResult Index() { int hour = DateTime.Now.Hour; ViewData["Greetings"] = (hour < 12 ? "Good Morning" : "Good Afternoon"); ViewBag.Greetings = (hour < 12 ? "Good Morning" : "Good Afternoon"); TempData["Greetings"] = (hour < 12 ? "Good Morning" : "Good Afternoon"); return View(); } |
Update your Index.aspx view template to display it as follows:
1 2 3 4 5 6 |
<body> @ViewData["Greetings"], Deccansoft (from the view)! @ViewBag.Greetings, Deccansoft (from the view)! @TempData["Greetings"], Deccansoft (from the view)! @Html.ActionLink("Postback For TempData", "TempDataDemoView") </body> |
1 2 3 4 5 6 7 8 |
public ViewResult TempDataDemoView() { var vd = ViewData["Greetings"]; var vb = ViewBag.Greetings; var td = TempData["Greetings"]; return View(); } Put a break point and observe that vd, vb are null but td is not. |
TempData.Keep(); – To retain key in TempData in subsequent round trip
Note: TempData uses HttpSession and can be demonstrated by disabling session in web.config
<sessionState mode=”Off”></sessionState>
If you are interested in developing dynamic websites and web applications using ASP.NET Framework, learning ASP.NET Web Forms from BestDotNetTrainingās online training would be of great use. And C# is the best choice of a programming language used for writing code in ASP.NET websites.
Web Forms is one of the 3 programming models for creating ASP.NET websites and web applications. The other two programming models are Web Pages and MVC (Model, View, and Controller).
