dotnet / dotnet/aspnetcore

Model binding fails with FormatException if dictionary key is numeric type and value is missing from POST

Open
#35,594 9 comments 0 reactions 0 assignees View on GitHub
area-mvc bug feature-model-binding
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 10h
Merged PRs (30d)
281

Description

### Describe the bug

In ASP.net, it is possible to POST a dictionary in a form submission in the following format:

```

```

This will be bound correctly to a controller action like this:
```
public async Task TagDetails(Dictionary sortOrder)
```

However, if the sortOrder field is completely missing from the POST, such as is very likely to happen if this data comes from a database and the list to sort is empty, the controller action crashes with a validation error IF the key in the dictionary is a numeric type like int/long/float/decimal OR a field that requires parsing, like DateTime.

If we attempt to map it to a Dictionary we see the error as "FormatException: The string 'submit' was not recognized as a valid DateTime. There is an unknown word starting at index '0'.". For numbers, the error is a similar parsing error. Depending on what the form looks like the name of the field it attempts to parse ("submit") in the example above is different, so it happens regardless of whether this list is the only thing on the form or not.

It seems that ASP.net is attempting to over-parse this, because surely it should be attempting to parse only named parameters if it's a form being posted? If the type is int[] or List or similar it works fine (the parameter becomes null, as expected).

### To Reproduce

Repro attached for ASP.net Core 5.

[dictionary_parse_bug.zip](https://github.com/dotnet/aspnetcore/files/7027457/dictionary_parse_bug.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.