开发者

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 = Enti开发者_JAVA百科ty.SearchJob. Please help me. What am I doing wrong?


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.


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜