Skip to content

Instantly share code, notes, and snippets.

@ichiroku11
Created July 27, 2018 01:56
Show Gist options
  • Save ichiroku11/07061ce6a0ea1f8a417a71544dac3417 to your computer and use it in GitHub Desktop.
Save ichiroku11/07061ce6a0ea1f8a417a71544dac3417 to your computer and use it in GitHub Desktop.
ASP.NET Core MVC - TempDataにオブジェクト
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