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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With