Passing object in RedirectToAction

I want to pass object in RedirectToAction. This is my code:

RouteValueDictionary dict = new RouteValueDictionary();
            dict.Add("searchJob", searchJob);
            return RedirectToAction("SearchJob", "SearchJob", dict);

where searchJob is instance of SearchJob. But I don’t get data on SearchJob action method. Instead I get querystring of searchJob = Entity.SearchJob. Please help me. What am I doing wrong?


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can not pass classes to the redirected actions like that. Redirection is done by means of URL. Url is a string, so it can not contain classes (serializing objects to url is really out of logic here)

Instead, you could use TempData

TempData["searchJob"] = searchJob;
return RedirectToAction ...;

and in Action redirected

Entity.SearchJob = (Entity.SearchJob)TempData["searchJob"] ;

After executing of the code above, TempData will not contain searchJob anymore. TempData is generally used for single time reading.

But I do not like the way above. If I were in your place and wanted to search jobs by name, I would add route parameters like

RouteValueDictionary dict = new RouteValueDictionary();
dict.Add("searchJobName", searchJob.JobName);

and receive it to action via parameter

public ActionResult SearchJob(string searchJobName)
... do something with the name

This way, you get better user and HTTP friendly URL and from the Action point of view, it would get all the parameters it needs from outside. This is better for testing, maintenance, etc.

Method 2

You might try:

return RedirectToAction("SearchJob", "SearchJob", new RouteValueDictionary(searchJob))

Passing the searchJob object into the RouteValueDictionary constructor will decompose the searchJob object and pass each property of the SearchJob class as a top-level route value.

With the default model binder, an action defined as:

public ActionResult SearchJob(SearchJob searchJob)

Will receive a fully re-hydrated SearchJob object.

Method 3

You can not pass classes to RedirectToAction method, if you want to pass an entire object in a querystring or via POST you can serialize the object using XML or JSON and deserialize the object in the receiver controller.
If you use this approach to be careful on the size of the object serialized.

Method 4

Try to use Cross-Page Posting you can determin Prevoiuse page type, and use it object.

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x