ASP.NET MVC - TempData - Good or bad practice

anonymous picture anonymous · Dec 22, 2008 · Viewed 57k times · Source

I'm using the AcceptVerbs method detailed in Scott Gu's Preview 5 blog post for dealing with form entries in ASP.NET MVC:

  • User gets an empty form via GET
  • User posts the filled in form via POST to the same Action
  • The Action validates data, takes appropriate action, and redirects to a new view

So I don't have to use TempData. That said, I now have to add a 'confirm' step to this process, and it seems to require the use of TempData.

For some reason, I have an aversion to using TempData -- that it is something to be designed around.

Is this at all a valid concern, or am I making it up?

Answer

JasonD picture JasonD · Feb 19, 2009

No need to have an aversion to TempData... But if not used correctly it could surely be an indication of poor design. If you are using RESTful URL's, TempData is a best practice for transfering messages from your POST Actions to your GET Actions. Consider this:

You have a form at URL Products/New. The form Posts to Products/Create, which validates the form and creates the Product, On Success the Controller redirects to URL Products/1 and on error would redirect back to products/New to display Error Messages.

Products/1 is just the standard GET action for the product, but we would like a message to display indicating the insert was a success. TempData is perfect for this. Add the message to TempData in the Post Controller and put some if logic in the view and your done.

On failure I've been adding the values entered in the formCollection and a collection of error Messages to TempData in the Post Action, and redirecting to the intial Action Prodcuts/New. I've added logic to the view to populate the form inputs with the previously entered values along with any error messages. Seems nice and clean to me!