I want to pass a class object from one controller action to different controller's action.
Sender Action
public class CourseController : Controller
{
[HttpPost]
public ActionResult CreateNewCourse(CourseViewModelBase courseViewModel)
{
if (ModelState.IsValid)
{
// Do some stuff
return RedirectToAction("CreateNewProject", "Project",
new { courseVM = courseViewModel});
}
// Bad happened
return View("CreateNewCourse", courseViewModel);
}
Receiver Action
public class ProjectController : Controller
{
[HttpGet]
public ActionResult CreateNewProject(CourseViewModelBase courseVM)
{
// Use CourseVM data and do other stuff
return View("Create", projectCreateViewModel);
}
}
I am getting data properly in Sender Action and Receiver Action is called properly from the redirect to action call. However courseVM in Receiver Action is null.
I know this is a very old question and had been asked repetitively. But I found that most of the answers suggested to use TempData
and were answered in 2008/2009. I believe there would be someway to pass data using RedirectToAction without using TempData
. If there is not then I would go with TempData only.
Finding
If I pass some simple data e.g. new {id = courseViewModel.CourseDuration}
and change the argument in Receiver action to id then id is properly received.
Similar Questions
Question 1
Question 2
Question 3
Question 4
Question 5
Question 6, tried to use this one but did not workout
Question 7
Question 8
Question 9
Question 10
Most of the answers in above questions are dated back in 2008/09 and uses tempdata.
This question itself is now about a year old, but I came across it so I thought I would help out others who come across it in the future. The accepted answer doesn't work - the complex object still arrives at the receiving action null.
I found that this answer from 2012 is still valid. You just can't pass complex objects in an HttpGet request (by nature this is what a RedirectToAction is - again, not something you can change). You can only pass scalar values: int, string, etc.
Make sure you've ruled out the below two options:
return View("ReceivingViewName", viewmodel)
Again, will only work for some situations, more than likely you'll need the other action and thus will need the Redirect, but worth remembering as a possiblity.If you can't get around the problem, and have eliminated the two above options, your options are:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With