【问题标题】:Redirect to action with parameters always null in mvc在 mvc 中重定向到参数始终为 null 的操作
【发布时间】:2015-03-07 10:09:10
【问题描述】:

当我尝试重定向到操作时,收到的参数始终为空?我不知道为什么会这样。

ActionResult action1() {
    if(ModelState.IsValid) {
        // Here user object with updated data
        redirectToAction("action2", new{ user = user });
    }
    return view(Model);
}

ActionResult action2(User user) {
    // user object here always null when control comes to action 2
    return view(user);
}

对此我还有一个疑问。当我使用路由访问操作时,我只能通过RouteData.Values["Id"] 获取值。路由的值不会发送到参数。

<a href="@Url.RouteUrl("RouteToAction", new { Id = "454" }> </a>

我想念任何配置吗?或任何我想念的东西。

ActionResult tempAction(Id) {
    // Here Id always null or empty..
    // I can get data only by RouteData.Values["Id"]
}

【问题讨论】:

  • 有时由于以下原因可能会发生这种情况。我们的自定义路由必须放在下面的默认路由之前才能正确识别。 routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "controller ", action = "action ", id = UrlParameter.Optional } );

标签: asp.net-mvc-4


【解决方案1】:

您不能在这样的 url 中传递复杂的对象。您必须发送其组成部分:

public ActionResult Action1()
{
     if (ModelState.IsValid)
     {
           // Here user object with updated data
           return RedirectToAction("action2", new { 
               id = user.Id, 
               firstName = user.FirstName, 
               lastName = user.LastName, 
               ...
           });
     }
     return view(Model);
}

另外请注意,我添加了return RedirectToAction,而不是只调用RedirectToAction,如您的代码所示。

但更好的方法是只发送用户的 id:

public ActionResult Action1()
{
     if (ModelState.IsValid)
     {
           // Here user object with updated data
           return RedirectToAction("action2", new { 
               id = user.Id, 
           });
     }
     return view(Model);
}

并在您的目标操作中使用此 ID 从存储此用户的任何位置(可能是数据库或其他东西)检索用户:

public ActionResult Action2(int id)
{
    User user = GetUserFromSomeWhere(id);
    return view(user);
}

一些替代方法(但我不推荐或使用的一种)是将对象持久保存在 TempData 中:

public ActionResult Action1()
{
     if(ModelState.IsValid)
     {
           TempData["user"] = user;
           // Here user object with updated data
           return RedirectToAction("action2");
     }
     return view(Model);
}

在你的目标行动中:

public ActionResult Action2()
{
    User user = (User)TempData["user"];
    return View(user);
}

【讨论】:

  • 谢谢@Darin Dimitrov,你能解释一下为什么不推荐使用TempData
  • 我只是将一个复杂对象传递给重定向操作,它将所有属性作为查询字符串参数附加到 url。
  • @Legends 怎么样?除非我将其分解为一个级别,否则我无法传递一个复杂的对象。没有完全分解,而是分成两个更小的复杂对象。好奇怪。
  • 我不得不使用 TempData,因为 RedirectToAction 在到达目标 Action 之前会转到 Log 函数,所以它在途中丢失了。 TempData 确保它可用。从 TempData 变量中提取数据后,我立即将其设置为 null!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-04
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
  • 1970-01-01
相关资源
最近更新 更多