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

Thursday, January 31, 2008

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! 

One Comment

  1. http:// says:

    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

Leave a Reply