ASP.NET Core 5 MVC not able to model bind DateTime property of my DTO ? Is there any known problem with ASP.NET core model binding process?

Here's my scenario -

I am trying to post a json object with below structure using angular 12 to MVC controller action method.

public class Student{
   public string FullName {get;set;}
   public int Age {get;set;}
   public DateTime BirthDate {get;set;}
}

I have decorated my MVC action method parameter using [FromBody] attribute.

However, when I try to post the json object to my action, the model just refuses to bind (model object is null)

Next, I tried changing the BirthDate from DateTime => string and observed that model gets bound correctly.

Is there any known issue with model binder OR am I missing any configuration that I need to enable related to datetime ?

My Action

[HttpPost]
public JsonResult Save1([FromBody] Student st) 
{ 
  return Json(st); 
}

Angular code

this._http.post<any>("../../TupleBinderAPI/Save1", {
  fullName: this.FullName,
  age: this.Age,
  birthDate: this.BirthDate
}, {
  headers: {
    ["Content-Type"]: "application/json; charset=UTF-8"
  }
}).subscribe((data: any) => {

  console.log(data);
});

Solution 1:

I test in my side and I found that, when I set the input value as "2020-1-12", it won't bind the DateTime type, but can bind string.

But, if I set the value as "2020-01-12", then it can bind to DateTime type successfully.

As I didn't find any official document to tell about it, so in my humble opinion, your issue may come from the incorrect format of the this.BirthDate, you may check the variable's value. We usually format the DateTime to "yyyy-MM-dd", so like this kind of string format may can be convert to DateTime type automatically, but some other format can't. If you insist on using your format of the data time, you may use custom model binding here, but I think it will cause more work.

enter image description here

enter image description here

Solution 2:

problem already diagnoses by Wang and explain in detail. you need to change date format from angular before sending data to service.

you can use DatePip Module - https://angular.io/api/common/DatePip

below is the sample code for changing date format.

import { DatePipe } from '@angular/common'
...
constructor(public datepipe: DatePipe){}
...
myFunction(){
 this.date=new Date();
 let latest_date =this.datepipe.transform(this.date, 'yyyy-MM-dd');
}

you can view the below thread How to convert date into this 'yyyy-MM-dd' format in angular 2