【发布时间】:2014-04-03 12:42:33
【问题描述】:
我有一个 Save 方法,它有一些额外的服务器端验证。如果失败,我想在浏览器中维护“/Edit/id” URL,以便刷新将保留在页面上。 (如果在这种情况下无法做到这一点,请告诉我。)
以下是我现在如何尝试执行此操作的简要视图:
[HttpPost]
public ActionResult Save(UserEditModel model) {
try {
repository.SaveUser(model.CopyTo());
}
catch (InvalidOperationException ex) {
// Doing this to just display it at the top of the page as it is not property-specific.
TempData["UserError"] = ex.Message;
// Doing this to maintain the "Edit/id" URL.
return RedirectToAction("Edit", "Users", new { id = model.Id });
}
// Want to keep the URL on the Index page as "Users", instead of "Users/Save".
return RedirectToAction("Index", "Users", new { page = model.Page });
}
除了 URL,我遇到的最大问题是,因为我正在重定向,所以我也会丢失用户在保存尝试失败时已经在字段中输入的所有数据。
我已经尝试将一个可选的UserEditModel 参数添加到默认为 null 的 Edit 操作,但是当从页面上的链接导航到 Edit 操作(而不是从 Save 操作重定向)时,可选的 Model 参数正在获取默认为new UserEditModel(),而不是我在参数列表中给出的默认值null。
【问题讨论】:
标签: c# asp.net-mvc-4 controller url-redirection