views:

30

answers:

1

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.

A: 

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
Clicktricity
In which case I would recreate the entire "main" view model in step 3, and pass along the errors in TempData?
PolishedTurd
You have 2 choices. Populate TempData with your errors, and then call RedirectToAction(ActionName) where this is the original GET action that displays the page, and presumably populates the view model appropriately. One problem with this method is that the User's 'invalid' values will be lost and original data will be desplayed on the page (which sometimes may be ok). The alternative is to (unfortunately) repopulate the entire model, and the errors and redisplay the page. If this approachintroduces repetition, then pull out the model populating code into a reuseable function.
Clicktricity
I see. Thanks for the explanation.
PolishedTurd