加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-15 23:12:48 所属栏目:asp.Net 来源:网络整理
导读:当我尝试重定向到动作时,我收到的参数始终为null?我不知道为什么会这样发生. ActionResult action1() { if(ModelState.IsValid) { // Here user object with updated data redirectToAction("action2",new{ user = user }); } return view(Model);}ActionRe
当我尝试重定向到动作时,我收到的参数始终为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);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读