Skip to content

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

@andreas-traexler

Description

@andreas-traexler

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-mvcIncludes: MVC, Actions and Controllers, Localization, CORS, most templates

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions