use TempData in a Helper error: The name 'TempData' does not exist in the current context

eiu165 picture eiu165 · Jan 6, 2012 · Viewed 8.3k times · Source

I would like to access the TempData in my helper for a flash message (like in ruby)

I get a runtime error of

The name 'TempData' does not exist in the current context

my Flash.cshtml is as follows

@helper Show() 
{
    var message = "test message";
    var className = "info";

    if (TempData["info"] != null)
    {
        message = TempData["info"].ToString();
        className = "info";
    }
    else if (TempData["warning"] != null)
    {
        message = TempData["warning"].ToString();
        className = "warning";
    }
    else if (TempData["error"] != null)
    {
        message = TempData["error"].ToString();
        className = "error";
    } 

    <script>
        $(document).ready(function () {
            $('#flash').html('@HttpUtility.HtmlEncode(message)');
            $('#flash').toggleClass('@className');
            $('#flash').slideDown('slow');
            $('#flash').click(function () { $('#flash').toggle('highlight') });
        });
    </script>
}

in the layout i have

<section id="main">
    @Flash.Show() 
    <div id="flash" style="display: none"></div>
    @RenderBody()
</section>

Answer

Jahan picture Jahan · Jan 6, 2012

TempData belongs to ControllerBase class which is base class for controllers, it's not accessible to shared views which no controller is behind them,

One possible workaround is to pass the controller to your helper method or access it through HtmlHelper.

@helper SomeHelper(HtmlHelper helper)
{
  helper.ViewContext.Controller.TempData
}