In this article, you will learn how to pass or send data from one controller to another using TempData object in ASP.NET MVC.

What is TempData in ASP.NET MVC?

TempData is basically a property of the TempDataDictionary class. It stays for subsequent HTTP requests whereas the ViewData and ViewBag objects stay only for the current request. It is used to transfer data and as well as redirects. The TempData isn’t destroyed on redirection.

The data is stored as an object in TempData which needs to be cast to its original type while retrieving. It also requires verification against the NULL value.

Example of passing data between controllers in ASP.NET MVC

In the following example, we will create two controllers and a string value is set in the TempData object in the first controller (Controller A). The data is redirected to another controller and finally displayed in the view.

Controller A

    public class ControllerA : Controller
    {
       
        public ActionResult Index()
        {
            TempData["message"] = "Welcome to TutorialsPanel.com!";
            return new RedirectResult(@"~\B\");
        }
    }

Controller B

    public class ControllerB : Controller
    {
 
        public ActionResult Index()
        {
            return View();
        }
    }

Now show the Data in a view as shown below:

View

<div>
    <b>Message from Controller A:</b>
    <br />
    @TempData["message"];
</div>

Screenshot

Related Articles

Last modified: September 29, 2019

Comments

Write a Reply or Comment

Your email address will not be published.