Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
335 views
in Technique[技术] by (71.8m points)

c# - 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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...