简体   繁体   中英

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);
});

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.

在此处输入图像描述

在此处输入图像描述

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM