当我尝试重定向到操作时,当我收到?时该参数始终为空。我不知道为什么会发生这样的事情。
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);
}
对于这一点,我有了另一个疑问。当我使用route访问操作时,我只能通过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"]
}
发布于 2013-10-18 14:59:54
你不能像那样在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);
}
https://stackoverflow.com/questions/19443444
复制相似问题