Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
like image 773
eiu165 Avatar asked Jan 06 '12 18:01

eiu165


People also ask

How do you use TempData in razor view?

Passing the data from Controller to View using TempDataGo to File then New and select “Project” option. Then create the ASP.NET web application project as depicted below. Then select “Empty” and tick “MVC” then click OK. The project is created successfully.

Can we use TempData in Web API?

It uses the keyvalue for passing the data and it has a need for typecasting. TempData: TempData is a dictionary that is derived from the TempDataDictionary class. The tempData Dictionary object persists only from one request to the next. You can mark one or more keys for retention using the keep method.


2 Answers

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
}
like image 175
Jahan Zinedine Avatar answered Oct 09 '22 21:10

Jahan Zinedine


Just pass TempData to your helper.

The call to the helper in your layout will look like this.

@Flash.Show(TempData)

Your Flash.cshtml helper will look like this.

@helper Show(System.Web.Mvc.TempDataDictionary tempData)
{
    // The contents are identical to the OP's code,
    // except change all instances of TempData to tempData.
}
like image 45
Theophilus Avatar answered Oct 09 '22 21:10

Theophilus