Store complex object in TempData

后端 未结 3 708
攒了一身酷
攒了一身酷 2020-11-29 01:16

I\'ve been trying to pass data to an action after a redirect by using TempData like so:

if (!ModelState.IsValid)
{
    TempData[\"ErrorMessages\"] = ModelSta         


        
相关标签:
3条回答
  • 2020-11-29 01:43

    I can not comment but I added a PEEK as well which is nice to check if there or read and not remove for the next 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);
    }
    

    Example

    var value = TempData.Peek<ClassA>("key") where value retrieved will be of type ClassA
    
    0 讨论(0)
  • 2020-11-29 01:49

    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

    0 讨论(0)
  • 2020-11-29 01:50

    Using System.Text.Json in .Net core 3.1 & above

    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);
            }
        }
    
    0 讨论(0)
提交回复
热议问题