Store complex object in TempData

后端 未结 3 796
攒了一身酷
攒了一身酷 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:50

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

    using System.Text.Json;
    
        public static class TempDataHelper
        {
            public static void Put(this ITempDataDictionary tempData, string key, T value) where T : class
            {
                tempData[key] = JsonSerializer.Serialize(value);
            }
    
            public static T Get(this ITempDataDictionary tempData, string key) where T : class
            {
                tempData.TryGetValue(key, out object o);
                return o == null ? null : JsonSerializer.Deserialize((string)o);
            }
    
            public static T Peek(this ITempDataDictionary tempData, string key) where T : class
            {
                object o = tempData.Peek(key);
                return o == null ? null : JsonSerializer.Deserialize((string)o);
            }
        }
    

提交回复
热议问题