Almacenar objeto complejo en TempData

Almacenar objeto complejo en TempData

Puede crear los métodos de extensión como este:

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);
    }
}

Y puede usarlos de la siguiente manera:

Di objectA es de tipo ClassA . Puede agregar esto al diccionario de datos temporales usando el método de extensión mencionado anteriormente como este:

TempData.Put("key", objectA);

Y para recuperarlo puedes hacer esto:

var value = TempData.Get<ClassA>("key") donde value recuperado será del tipo ClassA


No puedo comentar, pero también agregué un PEEK, que es bueno verificar si está allí o leerlo y no eliminarlo para el próximo GET.

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

Ejemplo

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

Uso de System.Text.Json en .Net core 3.1 y superior

using System.Text.Json;

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

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

        public static T Peek<T>(this ITempDataDictionary tempData, string key) where T : class
        {
            object o = tempData.Peek(key);
            return o == null ? null : JsonSerializer.Deserialize<T>((string)o);
        }
    }