dotnet / dotnet/aspnetcore

DisplayAttribute on nullable variables is lost and ModelMetadata is set to default for variable type

Open
#18,031 2 comments 0 reactions 0 assignees View on GitHub
affected-very-few area-mvc bug feature-mvc-razor-views severity-nice-to-have
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 5h
Merged PRs (30d)
276

Description

### Describe the bug
When using DisplayAttribute on nullable variables, the ViewData.ModelMetadata is set to default model data for the generic variable type. This leads to any data set to ViewData.ModelMetadata.Name or ViewData.ModelMetadata.Description using DisplayAttribute is nulled.
Sorry if bad description (not sure all the technical terms to properly describe it)

### To Reproduce
A model like this will in `@Html.EditorFor(m => m)` (and the like) loose the `ViewData.ModelMetadata.Name` and `ViewData.ModelMetadata.Description` for the nullable Int32 (in this example)

``` C#
public class BugTestModel
{
[Display(Name = "This name is kept in ViewData.ModelMetadata", Description = "This description is kept in ViewData.ModelMetadata")]
public Int32 TestIntOne { get; set; }

[Display(Name = "This name is nulled in ViewData.ModelMetadata", Description = "This description is nulled in ViewData.ModelMetadata")]
public Int32? TestIntNull { get; set; }
}
```

### Further technical details
- ASP.NET Core version 3.1

- Include the output of `dotnet --info`
```
.NET Core SDK (reflecting any global.json):
Version: 3.1.100
Commit: cd82f021f4

Runtime Environment:
OS Name: Windows
OS Version: 10.0.18363
OS Platform: Windows
RID: win10-x64
Base Path: C:\Program Files\dotnet\sdk\3.1.100\

Host (useful for support):
Version: 3.1.0
Commit: 65f04fb6db

.NET Core SDKs installed:
3.1.100 [C:\Program Files\dotnet\sdk]

.NET Core runtimes installed:
Microsoft.AspNetCore.All 2.1.14 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All]
Microsoft.AspNetCore.App 2.1.14 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
Microsoft.AspNetCore.App 3.1.0 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
Microsoft.NETCore.App 2.1.14 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
Microsoft.NETCore.App 3.1.0 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]

Microsoft.WindowsDesktop.App 3.1.0 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App]
```

- The IDE (VS / VS Code/ VS4Mac) you're running on, and it's version
`Microsoft Visual Studio Community 2019 Version 16.4.2`

- Test project (showing error)
[BugTest.zip](https://github.com/aspnet/AspNetCore/files/4000947/BugTest.zip)

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.