ASP.NET MVC – TempData – Good or bad practice

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!

Leave a Comment