ASP.NET MVC [HttpPost] action accepts single objec

2019-07-23 18: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, 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:

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.

回答1:

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