views:

26

answers:

1

ASP.NET MVC 2.0

I'm doing Post-Redirect-Get, if I get errors on post, I need to include ModelErrors along for the ride to along -Redirect-Get route. I send it through 'TempData':

TempData["modelErors"] = 
    ModelState.
        Where(item => item.Value.Errors.Count > 0).
        ToDictionary(
            item => item.Key, 
            item => item.Value.Errors.Select(error=>error.ErrorMessage).ToList()
        );

And then reinsert it into a ModelState:

if (TempData.ContainsKey("modelErors")) {
    foreach (var errors in (IDictionary<string,IList<string>>) TempData["modelErors"]) {
        foreach (var error in errors.Value) {
            ModelState.AddModelError(errors.Key, error);
        }
    }
}

Is there a better way?

+2  A: 

You should really only PRG after a successful post. Otherwise it's fine to return from the post if there's an error.

Otherwise you need to use cookies, session or request variables to store that information for the next request.

In ASP.NET MVC2 by default I think TempData uses Session state to store the information for the next request.

Chad Moran
+1 Its true that you should only issue a get if the request is validated as ok.
Malcolm Frexner