In this article I will explain with an example, how to pass (send) Generic List collection from one Controller to Another in
ASP.Net MVC.
Model
The Model class consists of following classes and properties.
Customer
public class Customer
{
public int CustomerId { get; set; }
public string Name { get; set; }
public string Country { get; set; }
}
CustomerData
public class CustomerData
{
public string Json { get; set; }
}
Controllers
Source Controller
The Controller consists of following Action method.
Action method for handling GET operation
Inside this Action method, Generic List collection of Customer class is created with some dummy data.
Then, an instance of CustomerData Model class is created and the dummy data will be serialized to Json property of CustomerData object using the Serialize method of the JavaScriptSerializer class.
Finally, the page is redirect to FetchController.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
List<Customer>customerInfo = new List<Customer>();
customerInfo.Add(new Customer {CustomerId = 1, Name = "John Hammond" , Country = "United States" });
customerInfo.Add(new Customer {CustomerId = 2, Name = "Mudassar Khan", Country = "India" });
customerInfo.Add(new Customer {CustomerId = 3, Name = "Suzanne Mathews", Country = "France" });
customerInfo.Add(new Customer {CustomerId = 4, Name = "Robert Schidner", Country = "Russia" });
CustomerData customerData = new CustomerData();
customerData.Json = (new JavaScriptSerializer()).Serialize(customerInfo);
return RedirectToAction("Index", "Fetch", customerData);
}
}
Destination Controller
The Controller consists of following Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
Action method for handling GET operation
Inside this Action method, the CustomerData class object is retrieved and deserialized to Generic List collection of Customer class using the Deserialize method of the JavaScriptSerializer class.
public class FetchController : Controller
{
// GET: Fetch
public ActionResult Index()
{
return View();
}
[HttpGet]
public ActionResult Index(CustomerData customerData)
{
List<Customer> customers = (new JavaScriptSerializer()).Deserialize<List<Customer>>(customerData.Json);
return View();
}
}
View
Source View
There is no programming required inside the View and hence this section is skipped.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
</body>
</html>
Destination View
There is no programming required inside the View and hence this section is skipped.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
</body>
</html>
Screenshot
Downloads