I have a simple WebApi 2.1 project and am receiving a model state error when I post and leave the value for a non-required nullable field (double type) blank. I want to leave the xml element but allow it to be blank. I had assumed making the field nullable would handle this but instead, if I post with salary left blank, I receive the error (listed below). If I put a number in... such as <salary>32000</salary>
everything works as expected.
How can I allow a blank value for a nullable double and still pass model validation?
The error I receive:
System.Web.Http.ModelBinding.ModelError: "There is an error in XML document (1, 111)."
My Model:
public class Employee
{
[Required]
public string LastName { get; set; }
public string MiddleName { get; set; }
[Required]
public string FirstName { get; set; }
public double? Salary { get; set; }
}
My Controller Post Method:
public HttpResponseMessage Post([FromBody]Employee employee)
{
if (ModelState.IsValid)
{
string firstName = employee.FirstName;
string lastName = employee.LastName;
if (employee.Salary != null)
{
double? salary = employee.Salary;
}
return Request.CreateResponse(HttpStatusCode.OK);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.NoContent, ModelState);
}
}
Here is my actual Post (with headers listed):
Content-Type: application/xml
Accept-Language: en-us
Accept: application/xml
<Employee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<LastName>Charlie</LastName>
<MiddleName>Bravo</MiddleName>
<FirstName>Alpha</FirstName>
<Salary></Salary>
</Employee>