ASP.NET MVC [HttpPost] 操作接受单个对象,将验证错误吐回 ViewPage<CustomViewModel> [英] ASP.NET MVC [HttpPost] action accepts single object, spits back validation errors to ViewPage<CustomViewModel>
问题描述
我正在试验强类型视图模型、完整视图和部分视图的不同组合,同时使用 RenderPartial() 和 RenderAction().不过,我要问的表单发布场景是来自主"视图的场景——不是局部的.这个主视图的控制器构造了视图模型,该模型为部分视图提供了它们的模型.
I'm experimenting with different combinations of strongly typed view models, full views and partial views, using both RenderPartial() and RenderAction(). The form-post scenario I'm asking about, though, is one that comes from the "main" view--one that isn't a partial. This main view's controller constructs the view model that provides the partial views with their models.
[HttpPost] 动作也在主控制器中,并且接受单个对象:
The [HttpPost] action is also in the main controller, and accepts a single object:
[HttpPost]
public ActionResult Edit([Bind(Prefix="Book")]Book book)
当 ModelState 有效并且更新成功时,我使用 RedirectToAction(),这一切都很好.
When the ModelState is valid, and the update is successful, I use a RedirectToAction(), which is all fine.
然而,当 ModelState 出现错误时,我会尝试:
When there are errors in the ModelState, however, I attempt to:
Return View(book);
-当然,视图期望包含各种其他对象和选择列表等的主"视图模型对象,这就是问题所在.
-and the view, of course, is expecting the "main" view model object that contains all kinds of other objects and Select Lists, etc., which is the problem.
在这种情况下,人们是否将整个视图模型对象用作 [HttpPost] 操作的参数,以便在出现错误时将其传回?我知道这不可能是正确的,而是认为有一个我不知道的更简单的解决方案.
In this case, do people use the whole view model object as a parameter to their [HttpPost] action, so that they can pass it back if there is an error? I know this can't be right, but rather think there is an easier solution that I am unaware of.
推荐答案
一种值得考虑的常见模式是 PRG 或 Post-Redirect-Get.
One common pattern worth considering is PRG or Post-Redirect-Get.
如果验证失败,重定向到原始的 Get 操作,如果验证通过,则获取序列中的下一个页面.
If validation fails, redirect to the original Get action, if validation passes, GET your next page in the sequence.
- /products/create"的 HTTP GET,呈现创建"视图
- HTTP POST 到/products/submit"
- 验证失败,重定向到/products/create",呈现Create"视图
- HTTP POST 到/products/submit"
- 项目已创建,重定向到/products/confirm",呈现Confirm"视图
这篇关于ASP.NET MVC [HttpPost] 操作接受单个对象,将验证错误吐回 ViewPage<CustomViewModel>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!