How to pass multiple objects using RedirectToAction() in Asp.NET MVC?
asp.net, asp.net-mvc, asp.net-mvc-3, asp.net-mvc-4
Solution
You cannot pass objects to the RedirectToAction method. This method is designed to pass only parameters. So you will need to pass all the values you want to be emitted in the corresponding GET request:
return RedirectToAction("GetEmployees", new
{
DepId = dep.DepId,
DepName = dep.DepName,
CatId = cat.CatId,
RoleId = role.RoleId,
... so on for each property you need
});
But a better way is to only send the ids of those objects:
return RedirectToAction("GetEmployees", new
{
DepId = dep.DepId,
CatId = cat.CatId,
RoleId = role.RoleId
});
and then in the target controller action use those ids to retrieve the entities from your underlying datasore:
public ActionResult GetEmployees(int depId, int catId, int roleId)
{
var dep = repository.GetDep(depId);
var cat = repository.GetCat(catId);
var role = repository.GetRole(roleId);
...
}
Problem
I would like to pass multiple objects using redirectToAction() method. Below is the actionresult i'm redirecting to. ``` public ActionResult GetEmployees(Models.Department department, Models.Category category, Models.Role role) { return View(); } ``` I'd like to do something like the below ``` public ActionResult test() { Models.Department dep = new Models.Department(); Models.Category cat.......etc return RedirectToAction("GetEmployees", dep, cat, role); } ``` Any help would be greatly appreciated - thanks Updated Can I use something like ``` Models.Department dep = new Models.Department() { DepId = employee.DepartmentId }; Models.Category cat = new Models.Category() { CatId = employee.JobCategoryId }; Models.Role title = new Models.Role() { RoleId = employee.JobTitleId }; return RedirectToAction("GetEmployees", new { department = dep, category = cat, role = title }); ```