Mike Bosch's Blog on .NET

Agile enterprise architecture in .NET, SOA, WCF, WS-*, AJAX, MVC, Sharepoint and more...

ASP.NET MVC Tip #1 - Accessing TempData from a ViewUserControl

Scenario:

I've been creating several shared components that I use throughout the MVC application.  I found that almost all my forms needed some kind of feedback mechanism on whether the form was successful or not.  I created an ErrorDisplay ViewUserControl which is called on most form input pages using the MVC HTML helper:  <%= RenderUserControl("~/Views/Shared/ErrorDisplay.ascx") %>.

 

This simple control will check for a key in the TempData dictionary and if it finds it, it will loop through the items in that dictionary.  The item I store in the TempData is a dictionary of error messages added from the controller.  My issue in this case was that I kept getting a null reference exception when trying to access the TempData from the user control.

Solution:

On view pages, to access the TempData dictionary you can go through the ViewContext property directly.  However, from a view user control, we have to access it through the Html.ViewContext.TempData property.  This seems like a bug to me which I'm sure will be fixed in the next drop of the MVC framework.  Also, I believe that TempData will also be accessible directly as a property of the View Page in future releases.

Hope this helps! 

Posted: Jan 31 2008, 05:00 AM by MikeBosch | with 2 comment(s) |
Filed under: ,

Comments

Christopher Steen said:

Link Listing - January 31, 2008

# February 1, 2008 8:13 AM

Dave said:

Funny, I was experiancing the same problem with TempData. I assumed after a while that TempData is onyl available to the controller. My solution was to add an ErrorDictionary property of the BaseViewData class.

Sadly enough I don't have the time (or resources if you will) to analyze the MVC framework as I wanted too.

Thanks for your clearification about this subject.

Regards,

Dave

# February 6, 2008 6:50 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)