在 RedirectToAction 中传递对象 [英] Passing object in RedirectToAction

查看:34
本文介绍了在 RedirectToAction 中传递对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 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);

其中 searchJob 是 SearchJob 的实例.但是我没有获得有关 SearchJob 操作方法的数据.相反,我得到 searchJob = Entity.SearchJob 的查询字符串.请帮我.我做错了什么?

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?

推荐答案

您不能将类传递给这样的重定向操作.重定向是通过 URL 完成的.Url 是一个字符串,所以它不能包含类(将对象序列化为 url 在这里确实不合逻辑)

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)

相反,您可以使用 TempData

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

并在行动中重定向

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

执行上述代码后,TempData 将不再包含 searchJob.TempData 一般用于单次读取.

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);

并通过参数接收到动作

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

通过这种方式,您可以获得更好的用户和 HTTP 友好 URL,并且从 Action 的角度来看,它将从外部获取所需的所有参数.这更适合测试、维护等.

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.

这篇关于在 RedirectToAction 中传递对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆