3

Can't pass ModelState validation in WebApi application for object which contains nullable types and has null values. The error message is "The value 'null' is not valid for DateProperty."

The code of object:

public class TestNull
{
    public int IntProperty { get; set; }
    public DateTime? DateProperty { get; set; }
}

Controller:

public class TestNullController : ApiController
{
    public TestNull Get(int id)
    {
        return new TestNull() { IntProperty = 1, DateProperty = null };
    }

    public HttpResponseMessage Put(int id, TestNull value)
    {
        if(ModelState.IsValid)
            return Request.CreateResponse(HttpStatusCode.OK, value);
        else
        {
            var errors = new Dictionary<string, IEnumerable<string>>();
            foreach (var keyValue in ModelState)
            {
                errors[keyValue.Key] = keyValue.Value.Errors.Select(e => e.ErrorMessage);
            }

            return Request.CreateResponse(HttpStatusCode.BadRequest, errors);
        }
    }
}

Request:

$.getJSON("api/TestNull/1",
function (data) {
    console.log(data);
    $.ajax({
        url: "api/TestNull/" + data.IntProperty,
        type: 'PUT',
        datatype: 'json',
        data: data
    });
});
JackPoint
  • 4,031
  • 1
  • 30
  • 42
Denis
  • 89
  • 1
  • 8

2 Answers2

4

I just did a quick test in one my own WebAPI projects and passing null as a value for a nullable value-type works fine. I suggest you inspect the actual data that is being send to your server using a tool like Fiddler

Two valid scenarios that will work are:

{ IntProperty: 1, DateProperty: null } 
{ IntProperty: 1 } // Yes, you can simply leave the property out

Scenarios that will NOT work are:

{ IntProperty: 1, DateProperty: "null" } // Notice the quotes
{ IntProperty: 1, DateProperty: undefined } // invalid JSON
{ IntProperty: 1, DateProperty: 0 } // Will not be properly interpreted by the .NET JSON Deserializer 

If the two default scenario's do not work then I suspect your problem lies elsewhere. I.e. Have you changed any of the default settings of the JSON serializer in your global.asax?

Martin Devillers
  • 17,293
  • 5
  • 46
  • 88
  • 1
    Thank you Martin! The issue was in [Nightly build packages](http://aspnetwebstack.codeplex.com/discussions/353867) I applied to my project. GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore solved the problem – Denis Aug 13 '12 at 07:36
  • Thanks for giving such nice scenarios Martin.Vey helpful.Can you please tell me if I pass DateProperty:"" then should it ignore as null or not.Actually in my case it's ignoring as null value if I am not mistaken. – user3603255 Feb 05 '15 at 12:43
0

Almost 9 years later I'm still having similar problem in ASP.NET Core 3.1

But I've found a working workaround for me (just exclude null values from data being sent - as opposed to sending values as nulls).

See https://stackoverflow.com/a/66712465/908608

It's not a real solution, becasue backend still does not handle null values properly, but at least ModelState validation does not fail for nullable properties.

infografnet
  • 3,749
  • 1
  • 35
  • 35