开发者

ASP.NET MVC [HttpPost] action accepts single object, spits back validation errors to ViewPage<CustomViewModel>

开发者 https://www.devze.com 2023-01-17 03:45 出处:网络
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, thou

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.

The [HttpPost] action is also in the main controller, and accepts a single object:

    [HttpPost]
    public ActionResult Edit([Bind(Prefix="Book")]Book book)

When the ModelState is valid, and the update is successful, I use a RedirectToAction(), which is all fine.

When there are errors in the ModelState, however, I attempt to:

开发者_StackOverflow中文版
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.

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.


One common pattern worth considering is PRG or Post-Redirect-Get.

If validation fails, redirect to the original Get action, if validation passes, GET your next page in the sequence.

  1. HTTP GET of "/products/create", "Create" view is rendered
  2. HTTP POST to "/products/submit"
  3. Validation Fails, redirect to "/products/create", "Create" view is rendered
  4. HTTP POST to "/products/submit"
  5. Item is created, redirect to "/products/confirm", "Confirm" view is rendered
0

精彩评论

暂无评论...
验证码 换一张
取 消