Passing Data From One Controller To Another Controller In ASP.NET MVC

Introduction 

 
In this technique, you store the data to be passed in the TempData dictionary in the sender action method.
 
The receiving action method reads the data from the TempData dictionary.
 
You might be aware that the TempData dictionary can hold data until it is read, and this can carry data across multiple requests.
 
First we will create Customer Class.
  1. public class Customer {  
  2.  public int CustomerID {  
  3.   get;  
  4.   set;  
  5.  }  
  6.  public string CustomerName {  
  7.   get;  
  8.   set;  
  9.  }  
  10.  public string Country {  
  11.   get;  
  12.   set;  
  13.  }  
  14. }  
Following is the Source Action Code.
  1. public ActionResult Index() {  
  2.  Customer data = new Customer() {  
  3.   CustomerID = 1, CustomerName = "Abcd", Country = "PAK"  
  4.  };  
  5.  TempData["mydata"] = data;  
  6.  return RedirectToAction("Index""Home2");  
  7. }  
As you can see Index() action instantiates a Customer object as before.
 
This time, however, it stores the Customer object in a TempData key named mydata.
  
The RedirectToAction() method is then used to take control of the Index() action of the Home2 controller.
 
Inside the Index() of Home2, you can read the value as follows: 
  1. public ActionResult Index() {  
  2.  Customer data = TempData["mydata"as Customer;  
  3.  return View(data);  
  4. }  
The above code reads the Customer object from the TempData dictionary and passes it to the Index view.
 
The TempData technique doesn't require any additional setup but it requires that session state be enabled.
 
Also, TempData is designed to store arbitrary pieces of data. If you are planning to send model objects through TempData, that may be a deviation from standard design practice.


Similar Articles