asp.net-mvc-4 – 重定向到动作,参数在mvc中始终为空

当我尝试重定向到动作时,我收到的参数始终为null?我不知道为什么会这样发生.
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"]
}

解决方法

你不能传递这样一个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);
}

还要注意,我已经添加了返回RedirectToAction,而不是仅在代码中显示的方法调用RedirectToAction.

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

public ActionResult Action1()
{
     if (ModelState.IsValid)
     {
           // Here user object with updated data
           return RedirectToAction("action2",});
     }
     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);
}

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....