首页 新闻 赞助 找找看

MVC的RedirectToAction的问题

1
悬赏园豆:10 [已关闭问题] 关闭于 2012-02-07 14:08

遇到一个这样的问题:
使用强类型的RedirectToAction方式从一个action跳转到另一个action,需要在url中传一个复杂类型,可是发现redirect后url的参数是类型名而不是具体值,可能描述的不清楚,直接上代码

public class ComplexType
{
public DateTime DateTime1 { get; set; }
public DateTime DateTime2 { get; set; }
}

public ActionResult Action1()
{
ComplexType myType = new ComplexType()
{
DateTime1 = DateTime.Now,
DateTime2 = DateTime.Now
};
return this.RedirectToAction(controller => controller.Action2(myType));
}

public ActionResult Action2(ComplexType type)
{
return View();
}

调试会发现当执行RedirectToAction后url类似这样

http://localhost/Home/Action2?type=MVCApplication.HomeController.ComplexType

而不是希望得到的

http://localhost/Home/Action2?DateTime1=2011.10.XXXX&DateTime2=2011.10.XX

请问,这个问题如何解决?如果不用强类型当然好解决,可是感觉很不爽,求解

rad的主页 rad | 初学一级 | 园豆:28
提问于:2011-10-18 15:17
< >
分享
所有回答(4)
1

试试:

public ActionResult Action2(ComplexType type)
{
return View("action2?DateTime1="+type.DateTime1+"&DateTime2="+type.DateTime2);
}
artwl | 园豆:16736 (专家六级) | 2011-10-18 15:46

饿,用这种弱类型的方法肯定可行,例如

return RedirectToAction("Action2", new { DateTime1 = myType.DateTime1, DateTime2 = myType.DateTime2});

但是有没有更好的办法呢?

支持(0) 反对(0) rad | 园豆:28 (初学一级) | 2011-10-18 17:02
0

(1)Action1里直接return Action2(myType);不好吗?效果基本是一样的,为什么非要多一次跳转呢?

(2)你代码里的RedirectToAction方法的签名为什么我没见过?你确定不是你Controller基类里自己实现的吗?我是ASP.NET MVC 3,没看到这个签名的方法。

水牛刀刀 | 园豆:6350 (大侠五级) | 2011-10-19 18:14

1.不同controller就不行了,而且个人看来redirect更符合http的逻辑

2.在mvc future包里有提供强类型的重载

支持(0) 反对(0) rad | 园豆:28 (初学一级) | 2011-10-19 18:43
1

为什么把参数当强类型传递 ? 搞不明白

远非¢贤 | 园豆:390 (菜鸟二级) | 2011-11-08 11:16
1
重写ComplexType的ToString方法试试:

public
class ComplexType
{
public DateTime DateTime1 { get; set; }
public DateTime DateTime2 { get; set; }
public override string ToString(){
  return "DateTime1="+DateTime1+"&DateTime2="+DateTime2;
}
}
 
rulee | 园豆:212 (菜鸟二级) | 2012-05-14 15:04
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册