0

I am working on ASP.NET Core 6.0. I have to use TempData in my utility class. So, I am getting it from ITempDataDictionaryFactory as described at How to access TempData in my own utility class? Or TempData is null in constructor.

In my code, I am assigning a List<string> to the TempData. When I try to access it, I am getting a null value error. My code is shown below.

This is how I create and set a List<string> in the tempData:

var tempData = _tempDataDictionaryFactory.GetTempData(httpContext);

if (tempData["InvalidLoginNames"] is null)
{
    var InvalidLoginNames = new List<string>();
    InvalidLoginNames.Add(username.Trim());
    tempData["InvalidLoginNames"] = InvalidLoginNames;
}

This is how I try to get the value out:

var temp = tempData["InvalidLoginNames"] as List<string>;

When I try to get the saved value from temp, it throws error as it is null. Interestingly, when I however over it during debug, it has the value.

1 Answer 1

0

When I try to get the saved value from temp, it throws error as it is null. Interestingly, when I however over it during debug, it has the value.

Well, the link you have shared has used controller context or that particular service as a dependency.If your utility class needs to access TempData frequently and is tightly coupled with a specific controller, consider injecting the controller itself as a dependency.

In addition, based on your shared code it seems, utility class likely gets called outside the immediate context of a controller action. It would have been more convenient if you could shared your full implementation.

However, the reason you were not able to retrieve the value is all are not persistant data container. Once the action been redirected, data no longer would be either in Tempdata, viewdata or viewbag these are one time only.

In order to keep the data from one action to another action even after the page redirection you either could inject your utility as a dependency it self or easiest way to deal with it by using session state which is data persistant or can keep the data as long as you want.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.