Blog for Junior Developers C#/.NET

Sunday, May 12, 2024

ASP.NET MVC developers know that data can be passed from a controller to a view in a variety of ways. The most popular way is to use ViewModel, but you can also use ViewBag, ViewData and TempaData, among others, but what is the difference between these 3 methods? You will learn about it in this article. I will try to introduce you to these three approaches and show what the basic difference is between them.

difference-between-viewdata-viewBag-and-tempdata.jpg

Example 1


How does it look in practice:

//Controller:
using Microsoft.AspNetCore.Mvc;

namespace Demo.Controllers
{
    public class HomeController : Controller
    {    
        public IActionResult Index()
        {
            ViewData["Age"] = 32;
            ViewBag.Year = 2020;
            TempData["Number"] = 1;
            return View();
        }         
    }
}

//View:
<div>
    AGE => @ViewData["Age"] <br />
    YEAR => @ViewBag.Year <br />
    NUMBER => @TempData["Number"] <br />
</div>

//Result:
AGE => 32 
YEAR => 2020 
NUMBER => 1


As you can see in our first case, all the results are correct and as expected. So which way is the best and how do they really differ?


ViewData


ViewData is a dictionary whose values ​​we refer to by providing the appropriate key, which is a string. That is, in square brackets we provide the key itself and we assign a given value to this key; if we want to display the value, we also provide a string in such brackets, i.e. the key under which the value is located in this dictionary. We pass any type of object as the dictionary value. If we read a value from this dictionary, we also receive an object type, so ViewData usually requires us to cast it to another complex type. What is also important in the case of ViewData is the fact that its value is stored only within one request. If redirection occurs, the value will be deleted.


ViewBag


ViewBag is an improved version of ViewData. It is a wrapper on ViewData, which makes it a bit slower. It is a dynamic type, so we do not have to cast to the expected type every time. Like ViewData, the value is only stored within a single request. If we want to assign an object to ViewBag, just enter any name after a dot and assign it, just like we assign values ​​to object properties. We can also read the value in the view in the same way.


TempData


When it comes to TempData, we assign values ​​similarly to ViewData, because it is also a dictionary type. That is, after TempData we put a string in square brackets, which is a key containing some value. The key difference between TempData and ViewData is that redirection does not delete the TempData value. Data can be transferred between requests. This data is saved in the session.


Example 2


As you could see in the previous example, all data was displayed correctly. Let's look at the situation when our action redirects to another action. As you may have already guessed, not all data will be displayed correctly in this case:

//Controller:
using Microsoft.AspNetCore.Mvc;

namespace Demo.Controllers
{
    public class HomeController : Controller
    {    
        public IActionResult Home()
        {
            ViewData["Age"] = 32;
            ViewBag.Year = 2020;
            TempData["Number"] = 1;
            return RedirectToAction("Index");
        }

        public IActionResult Index()
        {
            return View();
        }
    }
}

//View:
<div>
    AGE => @ViewData["Age"] <br />
    YEAR => @ViewBag.Year <br />
    NUMBER => @TempData["Number"] <br />
</div>

//Result:
AGE =>
YEAR =>
NUMBER => 1


As we suspected, only the data passed via TempData in this case was passed correctly to the view.


SUMMARY


As you can see, we have several ways to pass data from the controller to the view. Today I presented you 3 popular methods that you will sometimes use. Each of these methods, as is most often the case, has several advantages and disadvantages. I hope you will know when to use which one depending on the situation. That's it for today, see you in the next post :)

Author of the article:
Kazimierz Szpin

KAZIMIERZ SZPIN
Software Developer C#/.NET, Freelancer. Specializes in ASP.NET Core, ASP.NET MVC, ASP.NET Web API, Blazor, WPF and Windows Forms.
Author of the blog CodeWithKazik.com

Previous article - Why is it worth becoming a .NET developer? Quick Analysis
Next article - Do You Really Know the Differences Between First vs FirstOrDefault vs Single vs SingleOrDefault?
Dodaj komentarz
© Copyright 2024 CodeWithKazik.com. All rights reserved. Privacy policy.
Design by Code With Kazik and Modest Programmer.