ASP.NET MVC: Models, ViewData, ViewBag, and TempData Explained

In ASP.NET MVC, efficiently passing data between controllers and views is crucial for robust application development. This blog explains the four primary methods for data transfer, highlighting their uses and differences.

Model: A strongly typed method and the recommended way for passing data. It allows for intelligent and compile-time checking.

ViewData: A dictionary object for passing data as key-value pairs. It is loosely typed, requiring casting in the view and lacks compile-time checking.

ViewBag: Similar to ViewData, it provides dynamic access to properties. It is also loosely typed and lacks compile-time checking.

TempData: Used to pass data from the current controller to the next request. TempData is backed by session state and is useful in redirect scenarios.

Models – A Strongly Typed Approach

In ASP.NET MVC, models play a crucial role in transferring data between controllers and views. This method ensures type safety, enhances code readability, and facilitates compile-time error checking.

Passing data from a Controller to a View using a Model is ideal for:

  • Single Object Transfer: Ideal for scenarios where you need to display details of a single model/entity, like showing a specific user’s profile.
  • List or Collection Transfer: Useful when dealing with multiple entities, such as displaying a list of products or user comments.

But, how can you set it up?

In the Controller, you need to define the model and pass it as a parameter to the View method. I am going to assume that I have a Url.cs class which looks like below:

public class Url
    {
        public int Id { get; set; }
        public string OriginalLink { get; set; }
        public string ShortLink { get; set; }
        public int NrOfClicks { get; set; }
    }

Now, in the Controller action, you need to create an object with or without property values and then pass that object to the View method.

 public class UrlController : Controller
    {
        public IActionResult Index()
        {
            var newUrl = new Url()
            {
                Id = 1,
                OriginalLink = "https://dotnethow.net",
                ShortLink = "dnh",
                NrOfClicks = 1
            };

            return View(newUrl);
        }
    }

that is all you need to do in the Controller level, but since you have now passed a parameter to the View, you need to update the View so it does accept a parameter. The parameter or the model passed to the view is of type Url, so in the view you need to define it using the @model keyword.

The updated view would look like below:

ο»Ώ@model Url

<h4>@Model.OriginalLink</h4>

The model of this view has been set using @model Url, and since that is the model, you can access the properties within <h4> using the @Model.

We did mention above that you can pass single objects, but also a list or a collection of objects. If we were to update the example above, then we would need to:

  1. Change the Controller View parameter
  2. Change the view @model definition to match the View parameter

Updated controller

 public class UrlController : Controller
    {
        public IActionResult Index()
        {
            var newUrls = new List<Url>{....}
            return View(newUrls);
        }
    }

Since I changed the View parameter to be List<Url> instead of Url, I need to reflect that in the View side as well. Updated View would look like below:

ο»Ώ@model List<Url>

@foreach(var link in @Model)
{
    <p>@link.OriginalLink</p>
}

Now, you can see that since the @model is set to List<Url> you can use a foreach loop to iterate the view model (List<Url>) and access the properties.

The model is the most recommended method for data passing in ASP.NET MVC. It is strongly typed, meaning the view is typed to a specific class or model. This approach enables intelligent code features and compile-time checking, enhancing code safety and clarity.

Check out this tutorial to learn through a real example

11. Using a Model to Pass Data to a View

ViewData – A Flexible Dictionary Object

In ASP.NET MVC, ViewData is a flexible tool used for passing data from a controller to a view. It functions as a dictionary, storing data in key-value pairs, where each key is a string. This makes it suitable for transferring simple, lightweight data. However, since ViewData stores data as objects, it’s loosely typed, meaning you need to cast data to the correct type in the view.

Additionally, you can dynamically add any number of properties to ViewData in the controller, which are then accessible in the view using their keys.

Since ViewData functions as a dictionary, if you want to set a value, you need to use a key and then use the same key in the View. You do not need to pass the ViewData as parameter of the View method.

Example:

public class UrlController : Controller
    {
        public IActionResult Index()
        {
            ViewData["BlogPostUrl"] = "https://dotnethow.net"
            return View();
        }
    }

Since you do not need to pass ViewData as View parameter you do not need to define any models in the View side either. In, the view you can access the dictionary key value as below:

<h4>@ViewData["BlogPostUrl"]</h4>

As you can see, it is really easy to use ViewData to pass data from a Controller to a View. Despite its ease of use, ViewData has its limitations. It’s ideal for small data transfers but not recommended for complex data structures. The data in ViewData is only available for the duration of a single HTTP request, so it’s not suitable for persisting data across requests either.

You need to be careful when you set the keys, as if the key does not match when you try to read the value you will not get any exceptions, it simply return null. While ViewData offers a straightforward approach for data passing in ASP.NET MVC, for more complex scenarios, using view models is often a better choice due to their robustness and type safety.

Check out this tutorial to learn through a real example

12. Using ViewData to Pass Data to a View

ViewBag: Dynamic Property Access

In ASP.NET MVC, ViewBag is a dynamic and flexible tool for passing data from a controller to a view. Unline ViewData, which uses a dictionary-like structure, ViewBag allows you to define and access properties dynamically. This means you can create and use properties on the fly without predefining them, making it ideal for transferring straightforward, lightweight data.

Another advantage of being dynamic is that ViewBag does not require casting of data types when accessing its properties in the view, as it is loosely typed.

If you were to convert the ViewData example above to use ViewBag, the controller would look like below:

public class UrlController : Controller
    {
        public IActionResult Index()
        {
            ViewBag.BlogPostUrl = "https://dotnethow.net"
            return View();
        }
    }

and the View needs to be updated to look like below:

<h4>@ViewData.BlogPostUrl</h4>

As you can see from the example above, the dynamic nature of ViewBag simplifies the process of passing data, as there’s no need to use specific keys.

However, like ViewData, ViewBag has its limitations. It is well-suited for simple data transfers but may not be the best choice for handling complex data structures. The data in ViewBag is also limited to the scope of a single HTTP request, meaning it’s not suitable for maintaining data across multiple requests.

One key aspect to remember with ViewBag is its dynamic nature. Since it doesn’t require predefined keys, you can add properties as needed. However, if you try to access a property that hasn’t been set, ViewBag will simply return null without throwing any exceptions. This behavior necessitates careful handling to avoid runtime errors.

To see ViewBag in action and learn more about its practical applications, check out this tutorial for a real example.

13. Using ViewBag to Pass Data From a Controller to a View

TempData: Ideal for Redirects

TempData stands out in ASP.NET MVC as a solution for persisting data across two consecutive HTTP requests. This feature is particularly useful for scenarios like displaying success messages after form submissions. Unlike ViewData and ViewBag, which are limited to a single request, TempData uses session state to keep data accessible even after the initial request, making it ideal for redirect scenarios.

Additionally, TempData is designed for automatic cleanup, deleting stored information after it’s accessed in the following request. In the example below, In the Create action I have set values for ViewData, ViewBag and TempData. Then, I redirect the user to the Index action, where I return the View

public class UrlController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Create()
        {
            ViewData["ViewDataMessage"] = "Success from ViewData!";
            ViewBag.ViewBagMessage = "Success from ViewBag!";
            TempData["TempDataMessage"] = "Success from TempData!";

            return RedirectToAction("Index");
        }
    }

Now, in the View, I will try to access all the values I have set one request before.

<h4>@ViewData["ViewDataMessage"]</h4>
<h4>@ViewBag.ViewBagMessage</h4>
<h4>TempData["TempDataMessage"]</h4>

When you run the application, in the view, you will only see the TempData value. This emphasizes that TempData values persist in the subsequent request, but only within that single subsequent request.

To see TempData in action and learn more about its practical applications, check out this tutorial for a real example.

14. Using TempData to Pass Data from a Controller to a View

Conclusion

In conclusion, model data passing provides type safety and clarity, ViewData and ViewBag offer simplicity for single-request data transfer within a controller and view, while TempData excels in retaining data across a single subsequent request, making it valuable for redirect scenarios. Understanding the strengths and limitations of each method is essential for effective data management in ASP.NET MVC applications, allowing you to choose the most suitable approach for your specific needs.

If you’re interested in building a comprehensive application using ASP.NET MVC, please take a look at the demo below:

Application Demo - Create Your Own URL Shortener with ASP.NET MVC and Web API Tutorial

Image by storyset on Freepik


Enjoyed this post? Subscribe to my YouTube channel for more great content. Your support is much appreciated. Thank you!


Check out my Udemy profile for more great content and exclusive learning resources! Thank you for your support.
Ervis Trupja - Udemy



Enjoyed this blog post? Share it with your friends and help spread the word! Don't keep all this knowledge to yourself.