Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access TempData in my own utility class? Or TempData is null in constructor

I use TempData in some of my Views/Actions but I'd like to extract that into some class. The problem is if I try to create my class in Controller's constructor, the TempDate there is null. Better yet, I'd like to have my class to be injectable into Controller. So I need to get access to TempData when my class is created.

So how can this TempData be constructed in a separate class?

This is ASP.NET Core 2.0 web app.

like image 894
alvipeo Avatar asked Sep 11 '17 22:09

alvipeo


People also ask

How do I pass TempData to view?

Passing the data from Controller to View using TempData Go 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 access TempData in JavaScript?

TempData is created on Server Side of the Web application and hence it is not possible to directly set it on Client Side using JavaScript or jQuery. Thus, only possible way is to set it by making an AJAX call to the Controller's Action method using jQuery AJAX function in ASP.Net MVC Razor.

Where is TempData stored?

By default TempData uses the ASP.NET Session as storage. So it is stored on the server ( InProc is the default).


1 Answers

You can access temp data anywhere by simply injecting ITempDataDictionaryFactory where you need it. You can then call its GetTempData which returns an ITempDataDictionary which you can use to access (read or write) the temp data for the current HTTP context:

public class ExampleService
{
    private readonly IHttpContextAccessor _httpContextAccessor;
    private readonly ITempDataDictionaryFactory _tempDataDictionaryFactory;

    public ExampleService(IHttpContextAccessor httpContextAccessor, ITempDataDictionaryFactory tempDataDictionaryFactory)
    {
        _httpContextAccessor = httpContextAccessor;
        _tempDataDictionaryFactory = tempDataDictionaryFactory;
    }

    public void DoSomething()
    {
        var httpContext = _httpContextAccessor.HttpContext;
        var tempData = _tempDataDictionaryFactory.GetTempData(httpContext);

        // use tempData as usual
        tempData["Foo"] = "Bar";
    }
}

Btw. the reason why TempData is null in your controller’s constructor is because the controller context is only injected after the controller has already been created (using property injection). So when the controller’s constructor runs, there simply isn’t any information about the current request yet.

If you do inject your service though, and that service works like the ExampleService above, then it will work even from within the constructor, since it will simply request the necessary information from the DI container itself (the factory and the HTTP context).

like image 141
poke Avatar answered Oct 07 '22 08:10

poke