Store Complex Object in Tempdata

Store complex object in TempData

You can create the extension methods like this:

public static class TempDataExtensions
{
public static void Put<T>(this ITempDataDictionary tempData, string key, T value) where T : class
{
tempData[key] = JsonConvert.SerializeObject(value);
}

public static T Get<T>(this ITempDataDictionary tempData, string key) where T : class
{
object o;
tempData.TryGetValue(key, out o);
return o == null ? null : JsonConvert.DeserializeObject<T>((string)o);
}
}

And, you can use them as follows:

Say objectA is of type ClassA. You can add this to the temp data dictionary using the above mentioned extension method like this:

TempData.Put("key", objectA);

And to retrieve it you can do this:

var value = TempData.Get<ClassA>("key")
where value retrieved will be of type ClassA

How to show deserialized TempData object in view?

Change your code from:

List<Products> products = JsonSerializer.Deserialize<List<Products>>(data);

To:

TempData["products"] = JsonSerializer.Deserialize<List<Products>>(data);

Or you can use return View(products) to use the data:

public IActionResult Index2()
{
var data = TempData["products"].ToString();
List<Products> products = JsonSerializer.Deserialize<List<Products>>(data);

return View(products);
}

View:

@model List<Products>
<ul>
@foreach (var item in Model)
{
<li>@item.ProductName</li>
}
</ul>

Passing Complex Object correctly without using TempData / ViewBag / ViewData

Normally, for web application, there're multiple options to store complex object depending on your need. I don't think there is a BEST way of doing, only the most suitable way and every solutions will come with PROS and CONS


SERVER SIDE

  • Session (I know you said cannot use session, but I just want to include it anyway): first option comes to mind, suitable for most web application. Since the modern web development are more on STATELESS, a lot of people want to avoid using Session at all cost. However, there're some specific infrastructure configuration to support session in STATELESS application such as distributed session or sticky session or you can save the session in a dedicated server or database.

    • PROS: easy to use, support web application naturally
    • CONS: need to configure a lot of things to work with STATELESS application
  • ANOTHER Dedicated server (Before anyone ask, I put it in the SERVER SIDE section even though it's another SERVER, but to me, whatever in our control is SERVER SIDE): a few options for you to choose here, first option could be to set up a cache server (Redis?) and retrieve/save using key (similar to session), or you can simply write an application to retrieve/save using your own logic.

    • PROS: reusability, extendability, works with all applications not just web, have its own scope
    • CONS: difficult to setup
  • Database: not a obvious choice, but database do support this kind of requirement

    • PROS: reusability, extendability, works with all applications not just web
    • CONS: performance issue
  • Other in-memory options (TempData, ViewBag, etc):

    • PROS: easy to use, well-supported with ASP.NET MVC
    • CONS: somtimes it's hard to pass around multiple views

CLIENT SIDE

  • There are so many options here to choose like use hidden fields, cookie, localStorage, sessionStorage, etc or even a simple query string will work
  • PROS: speed (since you don't need client-server transportation)
  • CONS: security (you cannot trust anything from client-side), not doing well with too complex object (heavy object), security (sensitive data), etc

SUGGESTED SOLUTION

I hope I understand your issue correctly but in my opinion, you should not store complex object, simply store the ID of the complex object in place of your choice, and make a query every time you need the object. So that your object is always up-to-date and you don't waste resource to store the complex object.

Hope it helps you.

Using TempData dictionary prevents RedirectToAction from working

It is not much of an answer, but I experienced the same issue with no resolution. I changed tempdata to a Session["rvm"] variable and was successful. Consider pivoting from tempdata to Session.

Storing list in TempData throwing exception

Your issue is caused by that TempData did not support complex type.

You could try to serialize the object to string and save it in TempData.

TempData["Products"] = JsonConvert.SerializeObject(productList);

Cannot pass complex object to another Action method

You are using the CookieTempDataProvider to manage TempData. Alas, it results in storing the TempData in cookies, as the name suggests.

The problem is that your data is too large to fit in the cookie. You may wish to use a different ITempDataProvider implementation (such as SessionStateTempDataProvider).

MVC Net Core Can TempData store Enumerables?

To be able to store data in sessions or temp data, the type must be serializable. IEnumerable<T> cannot be serialized. Try a List<T> instead.

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.1

Asp.Net core Tempdata and redirecttoaction not working

TempData uses Session, which itself uses IDistributedCache. IDistributedCache doesn't have the capability to accept objects or to serialize objects. As a result, you need to do this yourself, i.e.:

TempData["PopupMessages"] = JsonConvert.SerializeObject(_popupMessages);

Then, of course, after redirecting, you'll need to deserialize it back into the object you need:

ViewData["PopupMessages"] = JsonConvert.DeserializeObject<List<PopupMessage>>(TempData["PopupMessages"]);


Related Topics



Leave a reply



Submit