2

I have a View in MVC called Action, which accepts and ID as parameter. I also have another view called Action, but it is marked as HTTPPOST.

The POST version of Action can fail programatically. When it fails, I want to add a ModelError, and then Redirect to the GET version of Action, whilst I provide the ID .

In short => I want to transfer to a GET view from a POST view, and pass parameters. Something along the lines of

ModelState.AddModelError("", "Could not verify token");
return RedirectToAction("Action", "ExpiredAccounts" new { aid = myId });

Where Action is the View, ExpiredAccounts is the Controller and AID is the Account ID. This of course does not work since you can add a model error to a view, not redirecting

Thanks

4

1 回答 1

8

在这种情况下,您最好返回相同的视图,而不是重定向:

ModelState.AddModelError("", "Could not verify token");
var model = repository.Get(myId);
return View(model);

模式的正确流程Redirect-After-Post如下:

  1. GET 请求 -> 显示某种形式
  2. POST 请求 -> 表单被提交到服务器。这里有两种可能的情况:
    • 验证成功 => 重定向。
    • 验证失败 => 重新显示相同的视图,以便用户可以修复错误

如果您想违反此最佳实践,您始终可以在重定向时将错误消息作为查询字符串参数发送:

return RedirectToAction(
    "Action", 
    "ExpiredAccounts" 
    new { aid = myId, error = "Could not verify token" }
);

然后在目标操作中验证是否已提供此参数并将错误添加到模型状态:

public ActionResult Action(int myId, string error)
{
    if (!string.IsNullOrEmpty(error))
    {
        ModelState.AddModelError("", error);
    }
    ...
}
于 2013-05-18T05:58:28.430 回答