Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 237
Jaggu Avatar asked Sep 29 '11 13:09

Jaggu


People also ask

Can we pass model in RedirectToAction?

My Question - Can I pass student model in RedirectToAction? Since the route dictionary deals with objects, try changing the GetStudent action to accept an object and inside cast it to Student . Another option would be to serialize it using JSON when passing it from FillStudent .

What is difference between redirect and RedirectToAction?

RedirectToAction is meant for doing 302 redirects within your application and gives you an easier way to work with your route table. Redirect is meant for doing 302 redirects to everything else, specifically external URLs, but you can still redirect within your application, you just have to construct the URLs yourself.


2 Answers

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.

like image 39
Charlie Avatar answered Oct 11 '22 05:10

Charlie


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.

like image 65
archil Avatar answered Oct 11 '22 04:10

archil