dotnet / dotnet/aspnetcore

Confusing model binding / model validation behavior related to [Required] and value types

Open
#63,311 6 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

Hi, I have noticed somewhat confusing behavior regarding model binding / model validation and using value types together with the RequiredAttribute.

Given a controller action with the route `/test/{id?}` and a bound parameter `int id` and calling the controller with the url `/test`, it should not fail in model binding, because model binding assigns a default value to value types (id = 0).
The same way, using `string` instead of `int` fails, because the [Required] attribute is applied implicitly for non-nullable reference types.

It works as expected.

When I annotate the id parameter (`[Required] int id`) and I call the url `/test` it should not fail, because `[Required]` in model validation only checks for null (or an empty string) so all should be good.

But in reality, it fails, going completely against what the documentation describes how ((non-)nullable value types and the `[Required]` attribute work together in model binding / model validation.

Is the documentation out-of-date? Did I miss anything?

Any clarification would be appreciated.

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.