当我尝试重定向到操作时,我收到时参数总是为空?我不知道为什么会发生这样的事情.
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);
}
Run Code Online (Sandbox Code Playgroud)
有了这个,我还有另一个疑问.当我通过路径访问动作时,我只能通过获取值RouteData.Values["Id"].路由的值不会发送到参数.
<a href="@Url.RouteUrl("RouteToAction", new { Id = "454" }> </a>
Run Code Online (Sandbox Code Playgroud)
我错过任何配置?或者我想念的任何东西
ActionResult tempAction(Id) {
// Here Id always null or empty..
// I can get data only by RouteData.Values["Id"]
}
Run Code Online (Sandbox Code Playgroud)
Dar*_*rov 36
您不能在这样的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);
}
Run Code Online (Sandbox Code Playgroud)
另请注意,我已添加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);
}
Run Code Online (Sandbox Code Playgroud)
并且在您的目标操作中使用此ID从该用户存储的任何位置检索用户(可能是数据库或其他内容):
public ActionResult Action2(int id)
{
User user = GetUserFromSomeWhere(id);
return view(user);
}
Run Code Online (Sandbox Code Playgroud)
一些替代方法(但我不推荐或使用的方法)是将对象持久保存在TempData中:
public ActionResult Action1()
{
if(ModelState.IsValid)
{
TempData["user"] = user;
// Here user object with updated data
return RedirectToAction("action2");
}
return view(Model);
}
Run Code Online (Sandbox Code Playgroud)
并在你的目标行动中:
public ActionResult Action2()
{
User user = (User)TempData["user"];
return View(user);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
42866 次 |
| 最近记录: |