Class Serilization and Deserilization for Temp Data in Net Core 3.1
using HimanshuMorningCode.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace HimanshuMorningCode.Controllers
{
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);
}
}
[Route(“[controller]”)]
//[Route(“Form1”)]
public class Form1Controller : Controller
{
//[Route(“[controller]/[action]”)]
//[HttpGet]
[Route(“index”)]
//[Route(“[controller]/[action]”)]
public IActionResult Index()
{
return View();
}
//[HttpPost(“[controller]/index”)]
[HttpPost(“Index”)]
public IActionResult Index(IFormCollection obj)
{
// return Content(“Id=” + obj[“id”].ToString() + “, Name=” + obj[“name”].ToString() + ” Fathername is= ” + obj[“fname”].ToString());
Employee obj1 = new Employee
{
id = Convert.ToInt32(obj[“id”].ToString()),
name = obj[“name”].ToString(),
fname = obj[“fname”].ToString()
};
//TempData[“key1”] = obj1;
TempData.Put(“key1”, obj1);
return RedirectToAction(“Show”);
}
[HttpGet(“Show”)]
public IActionResult Show()
{
//Employee obj2 = (Employee)TempData[“key1”];
var obj2 = TempData.Get<Employee>(“key1”);
return View(obj2);
}
}
}