Datetime TempData error in C# .NET Core 6 and razor page

Remi 0 Reputation points
2023-12-20T01:53:50.27+00:00

TempData["abc"] = "2023-12-12" ; 

TempData["abc_raw"] = "2023-12-12 10:10:00 PM"; 

return RedirectToPage();

The two are the same, but there is a problem with TempData["abc"]. 

"abc" cause

System.InvalidCastException: Unable to cast object of type 'System.DateTime' to type 'System.String'.

Datetime to string cast error

So I temporarily used "abc" by serializing

TempData["abc"] = JsonSerializer.Serialize(TempData["abc"]);

Developer technologies ASP.NET ASP.NET Core
Developer technologies .NET Other
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.