I'm trying to make an HTTP request to my controller and send back a nullable DateTime. This request succeeds when the field is populated, when the field (CloseDate) is null, I get back an HTTP response saying null is not valid (for Close Date).
In my controller I have a post method that looks likes this:
[HttpPost]
[Authorize]
[Route("properties/{propertyId}")]
public async Task<IActionResult> BasicPropertyUpdate([FromForm] PropertyViewModel request)
{
}
Since I am getting a HTTP 400 response I don't get to hit any breakpoints.
In my ViewModel I have a contract that looks like this:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace ViewModels
{
public class PropertyViewModel
{
//other stuff
public DateTime? CloseDate { get; set; }
}
}
The raw HTTP response (as captured by Fiddler) looks like this:
HTTP/1.1 400 Bad Request
Date: Tue, 10 Dec 2019 22:07:01 GMT
Content-Type: application/json; charset=utf-8
Server: Kestrel
Vary: Origin
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:3000
Access-Control-Expose-Headers: TotalCount
Request-Context: appId=cid-v1:712f8d3d-6af6-44c6-a573-2b9adda915c7
Content-Length: 62
{"closeDate":["The value 'null' is not valid for CloseDate."]}
The form-data in my HTTP Request (as captured by Fiddler) looks like this:
-----------------------------32591187621655
Content-Disposition: form-data; name="closeDate"
null
Is there some kind of inherent limitation to [FromForm] that prevents sending of nullable DateTime fields? If so, is there some recommended alternative that gets the job done?
"null" is a JSON literal but a JSON deserializer isn't used to read the form data. It's being posted as a string of 4 characters.
The model binder will bind an empty string as null to a nullable value type such as DateTime?. If you were POST-ing the data as application/x-www-form-urlencoded, you could omit the name/value pair or specify an empty string (i.e. closeDate=).
This form data appears to be encoded as mime/multipart but the same principle holds. A zero-length mime part is an empty string, which the model binder can then interpret as null.
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