Search code examples
asp.net-mvchttp-redirectmodelstatetempdata

Concerns with using TempData


I'm using TempData to persist ModelState errors for a form which is rendered from a ChildAction. The form allows a user to post a comment on a blog post. If the ModelState isn't valid, the errors are copied to TempData and I redirect to my ShowPost action which displays the comment form, complete with validation errors, via the ChildAction.

My concern is that I'm actually redirecting twice in between saving the ModelState errors to TempData and redisplaying them in the ChildAction. This is because in my ShowPost action, I'm also checking to see if there is a valid slug matching the current post and then redirecting to include that slug if it's missing/incorrect. That means if a user posts a comment, they post to:

/posts/comment

which will redirect to:

/posts/1/

and then redirect to:

/posts/1/article-title

before the comment errors are displayed. This is working fine for me on my test server, but am I going to run into any particular problems with this second redirect? I'm asking because the posts/questions I've read are suggesting that TempData needs to be used straight after a redirect. If it isn't, the data may be lost between requests and I'm wondering if my second redirect could cause that.


Solution

  • In MVC 2 and 3 TempData is always available to access once. After you access a given key the temporary data is destroyed.