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

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

问题描述

我想通过对象RedirectToAction。这是我的code:

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通过来完成。链接字符串,因此它不能包含类(序列化对象的网址确实是在这里的逻辑的)

You can not pass classes to the redirected actions like that. Redirection is done by means of url. Url is 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"] ;

以上code的执行后,TempData的将不包含searchJob了。 TempData的通常用于单次读

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

但我不喜欢上面的方法。如果我处在你的位置,并想通过名称来搜索的工作的,我想补充routeParameters像

But I do not like the way above. If I were in your place, and wanted to search jobs by name, i would add routeParameters 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 name
}

这样,你会得到更好的用户和HTTP友好的URL,并从视图操作来看,它会得到它从外部需要的所有参数。这是用于测试,维护等更好。

This way, you get better user and http friendly url and from 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天全站免登陆