MVC Data Passing From One Controller To Another Controller

In this method, the sender action method has a TempData dictionary where the data that will be sent is stored.

The TempData dictionary is used to read the data via the receiving action method.

You may already be aware that the TempData dictionary has the ability to store data until it is read, allowing it to transfer information between requests.

We shall first build a Student Class.

public class Student{  
 public int StudentID {  
  get;  
  set;  
 }  
 public string StudentName {  
  get;  
  set;  
 }  
 public string Country {  
  get;  
  set;  
 }  
}

The Source Action Code is listed below.

public ActionResult Index() {  
 Student data = new Student() {  
  StudentID = 1, StudentName = "Abcd", Country = "PAK"  
 };  
 TempData["mydata"] = data;  
 return RedirectToAction("Index", "Home2");  
}

As you can see, the Index() operation again creates an instance of the Student object.

But this time, it saves the Student object under the mydata TempData key.

The RedirectToAction() function is then used to take control of the Index() action of the Home2 controller.

You may read the value within Home2’s Index() as follows:

public ActionResult Index() {  
 Student data = TempData["mydata"] as Student;  
 return View(data);  
}

The Student object is taken from the TempData dictionary by the code above and sent to the Index view.

While the session state must be enabled for the TempData method, no other setup is needed.

Additionally, TempData is made to hold any kind of data. It could be a divergence from best design practises to transfer model objects over TempData.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories