ViewData and ViewBag in Asp.net Core

ViewData and ViewBag in Asp.net Core
ViewData and ViewBag are mechanisms in ASP.NET Core MVC for passing data from your controller actions to your views. While they serve the same purpose, they differ in their implementation and syntax.
ViewData (Dictionary-Based):
It’s a dictionary-like object (ViewDataDictionary) that stores key-value pairs.
Keys are strings, and values can be of any type.
Access data using string keys: ViewData[“keyName”].
Requires casting when retrieving non-string values.
 
ViewBag (Dynamic):
It’s a dynamic wrapper around the ViewData dictionary.
Allows you to access data using dot notation: ViewBag.keyName.
No explicit casting is needed for non-string values.
 
 
Availability in Controllers and Views
Both ViewData and ViewBag are accessible in:
Controllers: You set values in the controller action and they are passed to the view.
Views: You retrieve values from the ViewData dictionary or the ViewBag dynamic object in the view to render content.
 
Code of ViewData:
// HomeController.cs (Controller)
ViewData[“appTitle”] = “Asp.Net Core Demo App”;
ViewData[“people”] = people;
 
// Index.cshtml (View)
<title>@ViewData[“appTitle”]</title>
List<Person>? people = (List<Person>?)ViewData[“people”];
 
 
Code of ViewBag:
// HomeController.cs (Controller)
ViewBag.appTitle = “Asp.Net Core Demo App”;
ViewBag.people = people;
 
// Index.cshtml (View)
<title>@ViewBag.appTitle</title>
@foreach (Person person in ViewBag.people)
 
Best Practices
Choose One: It’s generally recommended to pick either ViewData or ViewBag and use it consistently throughout your project to maintain a clear and unified approach.
Strong Typing with View Models: While ViewData and ViewBag offer flexibility, they lack compile-time type safety. For larger applications, prefer strongly typed view models to pass data to views.
Limited Scope: Understand that ViewData and ViewBag data exists only for the duration of the current request and response cycle. It’s not meant for persisting data between requests.
Meaningful Keys: Use descriptive and meaningful keys for your data to improve code readability.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply