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

前端之家收集整理的这篇文章主要介绍了asp.net-mvc-4 – 重定向到动作,参数在mvc中始终为空前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当我尝试重定向到动作时,我收到的参数始终为null?我不知道为什么会这样发生.
  1. ActionResult action1() {
  2. if(ModelState.IsValid) {
  3. // Here user object with updated data
  4. redirectToAction("action2",new{ user = user });
  5. }
  6. return view(Model);
  7. }
  8.  
  9. ActionResult action2(User user) {
  10. // user object here always null when control comes to action 2
  11. return view(user);
  12. }

而且我有另一个疑问.当我使用路由访问动作时,我只能通过RouteData.Values [“Id”]获取值.路由的值不发送到参数.

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

这里我想念任何配置?或任何我想念的东西

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

解决方法

你不能传递这样一个url中的复杂对象.你必须发送它的组成部分:
  1. public ActionResult Action1()
  2. {
  3. if (ModelState.IsValid)
  4. {
  5. // Here user object with updated data
  6. return RedirectToAction("action2",new {
  7. id = user.Id,firstName = user.FirstName,lastName = user.LastName,...
  8. });
  9. }
  10. return view(Model);
  11. }

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

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

  1. public ActionResult Action1()
  2. {
  3. if (ModelState.IsValid)
  4. {
  5. // Here user object with updated data
  6. return RedirectToAction("action2",});
  7. }
  8. return view(Model);
  9. }

并且在您的目标操作中,使用此ID从该用户存储的任何地方检索用户(可能是数据库或某些东西):

  1. public ActionResult Action2(int id)
  2. {
  3. User user = GetUserFromSomeWhere(id);
  4. return view(user);
  5. }

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

  1. public ActionResult Action1()
  2. {
  3. if(ModelState.IsValid)
  4. {
  5. TempData["user"] = user;
  6. // Here user object with updated data
  7. return RedirectToAction("action2");
  8. }
  9. return view(Model);
  10. }

并在您的目标行动中:

  1. public ActionResult Action2()
  2. {
  3. User user = (User)TempData["user"];
  4. return View(user);
  5. }

猜你在找的asp.Net相关文章