dotnet / dotnet/aspnetcore

property delcared with [TempData] does not work together with RedirectToPage if it contains date value

Open
#52,938 2 comments 0 reactions 0 assignees View on GitHub
area-mvc
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 6h
Merged PRs (30d)
290

Description

### Is there an existing issue for this?

- [X] I have searched the existing issues

### Describe the bug

I have a string property which is declared with `[TempData]` attribute, and I set the value with value "2023-12-12". It gives the error: `System.InvalidCastException: Unable to cast object of type 'System.DateTime' to type 'System.String'. ` when I use RedirectToPage.
BTW, it works fine if i set the value "2023-12-12 10:10:00 PM".

### Expected Behavior

It should render the value without any error

### Steps To Reproduce

Index.cshtml
```
@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
}

```
Index.cshtml.cs:
```
public class IndexModel : PageModel
{
public async Task OnGet()
{
}
[TempData]
public string abc { get; set; }

// [TempData]
// public string abc_raw { get; set; }

public async Task OnPostAsync()
{
abc = "2023-12-12"; // this caused cast error
//TempData["abc"] = "2023-12-12"; //this is fine
//abc_raw = "2023-12-12 10:10:00 PM"; // this is fine
return RedirectToPage();
}
}
```

### Exceptions (if any)

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

### .NET Version

.NET 5,6,7,8

### Anything else?

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.