Written by Mark Pringle | Last Updated on Thursday, December 01, 2022

MVC ASP.NET Version: 6.0 General Information

TempData is a storage mechanism provided by ASP.NET that sends data from the controller to the view or the view to the controller. TempData will also allow you to transfer data from one action method to another action method within a different or the same controller. 

Any data stored in TempData will only exist from the time of the request to the time the response is returned.

Using TempData to Transfer Data from the Controller to a View

In the example below, we are receiving a category and description from the database that matches our string and sending it to a view via TempData["Category"] and TempData["Description"].

        // GET: Search Results by Category
        public async Task<IActionResult> Category(string id)
        {
            if (!string.IsNullOrEmpty(id))
            {
                var category = await _context.CategoriesTable
                .FirstOrDefaultAsync(m => m.Category.ToLower() == id.Replace("-", " ").ToLower());

                TempData["Category"] = category?.Category;
                TempData["Description"] = category?.Description;

                if (!string.IsNullOrEmpty(id) && category?.Category.ToLower() == id.Replace("-", " ").ToLower())
                {
                    var results = await _context.SelectArticle.FromSqlInterpolated($"exec dbo.ArticleSelectCategory @category={id}").ToListAsync();
                    return View(results);
                }
                else
                {
                    return NotFound();
                }
            }
            else
            {
                return View();
            }
        }

In the view, we are using that TempData from the controller to determine what HTML elements the view renders. We use the TempData by adding an at-sign symbol  @ to the TempData.

@{
    if (@TempData["Category"] != null)
    {
        ViewData["Title"] = ViewData["Heading1"] = @TempData["Category"] + " ASP.NET Articles";
        ViewData["MetaDescription"] = @TempData["Description"];
    }
    else
    {
        ViewData["Title"] = ViewData["Heading1"] = "ASP.NET Articles by Categories";
        ViewData["MetaDescription"] = "Learn about building Web apps with ASP.NET Core and its associated technologies like React, Razor, MVC, Entity Framework, Microsoft SQL Server, and more.";
    }

    ViewData["ogimage"] = "https://www.learnaspnet.com/images/default.jpg";   
}

We are also using TempData to populate the active breadcrumb item.

        <nav aria-label="breadcrumb">
            <ol class="breadcrumb rounded-1 p-3" style="background-color:#efefef">
                <li class="breadcrumb-item te"><a href="/"><u>Home</u></a></li>
                <li class="breadcrumb-item"><a href="/category/"><u>Categories</u></a></li>
                <li class="breadcrumb-item active" aria-current="page">@TempData["Category"]</li>
            </ol>
        </nav>

Using TempData Within the Controller

In a controller, you can get/set or decorate a property using the TempData attribute. TempData properties can be used this way in controllers, Razor Pages, or models. Using TempData in this way allows you to transfer data from one action method to another within the same or different controller.

[TempData]
public string StatusMessage { get; set; }

This TempData can now be used in any action method thin the controller. 

            if (!result.Succeeded)
            {
                StatusMessage = "Error changing email.";
                return Page();
            }
            var setUserNameResult = await _userManager.SetUserNameAsync(user, email);
            if (!setUserNameResult.Succeeded)
            {
                StatusMessage = "Error changing user name.";
                return Page();
            }