Created
July 27, 2018 01:56
-
-
Save ichiroku11/07061ce6a0ea1f8a417a71544dac3417 to your computer and use it in GitHub Desktop.
ASP.NET Core MVC - TempDataにオブジェクト
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Threading.Tasks; | |
using Microsoft.AspNetCore.Mvc.ViewFeatures; | |
using Newtonsoft.Json; | |
namespace WebApp { | |
public static class TempDataDictionaryExtensions { | |
// TempDataにオブジェクトを書き込む | |
public static void SetObject<TObject>(this ITempDataDictionary tempData, string key, TObject obj) { | |
var json = JsonConvert.SerializeObject(obj); | |
// JSON文字列として書き込む | |
tempData[key] = json; | |
} | |
// TempDataからオブジェクトを読み込む | |
public static TObject GetObject<TObject>(this ITempDataDictionary tempData, string key) { | |
// JSON文字列として読み込む | |
var json = (string)tempData[key]; | |
return string.IsNullOrEmpty(json) | |
? default(TObject) | |
: JsonConvert.DeserializeObject<TObject>(json); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment