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
});
});
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:
Scenarios that will NOT work are:
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?