Error assigning null to a nullable int – “The value ‘null’ is not valid for property”

I have this property in my view model:

[DisplayName("Region")]
public int? RegionId { get; set; }

I pass my view model to my controller, and it fails at ModelState.IsValid if RegionId is null. If I pass an integer to it, it works fine.

The error message is:

The value ‘null’ is not valid for Region

I’ve also tried calling this before I check ModelState.IsValid, but I get the same error:

if (viewModel.RegionId == null)
    viewModel.RegionId = (int?)null;

What’s the problem here? Why can’t I assign null to something that is nullable?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Here’s another possible explanation.

I am AJAX POSTing to an MVC action method using jQuery like so:

$.post('url/here',dataObject);

jQuery will turn the data object into a query string. I use the default model binder to push the values into my ViewModel. Model validation fails with “The value ‘null’ is not valid for field name“. But the property is a nullable int. After inspecting the raw POST I find that the data object I am POSTing is serialized into a query string that looks like this:

Field1=null&Field2=value&Field3=value

and not this:

Field1=&Field2=value&Field3=value

So model validation is understandably complaining about assigning the string literal ‘null’ to my nullable int. One solution is to check for NULLs before POSTing. I wish I had time to dig in more but I just switched to sending a JSON representation of the data object which correctly handles the null values.

Method 2

In your Global.asax.cs file, in the Application_Start method, add the following line:

DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;

The issue is that, even for a nullable value type, by default, a “Required” attribute is added by the default ValidatorProvider.

Method 3

See here: ModelState validation fails for nullable types

The string “null” may be being passed. In my scenario I updated to an empty string “” and resolved this error.

Method 4

I think the issue is not assigning null, it’s that the consuming code does not except a null value. The assignment is perfectly valid (although your null check is inverted, and the cast is redundant).

viewModel.RegionId = null;

As an aside you can use HasValue to check for null on a nullable type. Although in reality this it’s no different to a null check, just looks a bit cleaner:

if (viewModel.RegionId.HasValue)
{
    // do something
}

Method 5

I had a problem with this.

My problem with this is that I was setting the offending property to null explicitly in the POST. So, akin to what you have, the request would’ve looked like:

RegionId = null

In my case, it was as simple as omitting the explicit declaration (e.g., don’t say it’s null, just don’t send any data)

Method 6

I have a feeling the problem lies somewhere out of the sample code you have shown. I have created a sample application that just creates a form and has a nullable field, but it works as expected. I would start eliminating other variables in your setup until you can to a working ViewModel with a nullable property, and you should be able to identify what is causing the problem.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x