当我尝试重定向到动作时,我收到的参数始终为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.
- 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);
- }