问题
Binding for kendo DatePicker has an error.
The 'value' should be a valid JavaScript Date instance
my web api in asp core to get a student is :
[HttpGet, Route("/api/master/{id}")]
public JsonResult GetStudentById(int id)
{
return Json(new { id = 1, RegisterDate = DateTime.Now });
}
it returns :
{"id":1,"registerDate":"2018-05-01T13:23:35.1229748+04:30"}
and finally in my angular component is :
student: Student = new Student();
constructor() { }
ngOnInit() {
this.http
.get(`http://localhost:58824/api/master/${10}`, { headers: this.setHeader() })
.subscribe(response => { this.student = response; });
}
view :
<form novalidate #form="ngForm" (submit)="save(form)">
<label for="birthDate">Date</label>
<kendo-datepicker [format]="'dd-MM-yyyy'" name="registerDate" [(ngModel)]="student.registerDate"></kendo-datepicker>
</form>
there is an error : The 'value' should be a valid JavaScript Date instance
needless to say, I have added DateInputsModule to imports array in app.module How can I fix it?
回答1:
This config removes the timezone (+04:30) from the serialized data:
services.AddMvc()
.AddJsonOptions(options =>
{
options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Unspecified; // Treat as a local time if a DateTime is being converted to a string.
});
Or try specifying the DateTimeFormat this way and make it automatically adjust dates to UTC by setting DateTimeStyles to AdjustToUniversal:
services.AddMvc()
.AddJsonOptions(options =>
{
var settings = options.SerializerSettings;
var dateConverter = new IsoDateTimeConverter
{
DateTimeStyles = DateTimeStyles.AdjustToUniversal,
DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ssK"
};
settings.Converters.Add(dateConverter);
});
回答2:
The value used in the kendo-datepicker
must be of type Date
but in your case it is a string
.
You need to convert it to a valid Date
object beforehand.
This can be done with e.g. a JSON Reviver, or by utilizing the IntlService.parseDate
method (Reference).
@Component({ ... })
public class MyComponent
{
value: Date;
valueString: string;
constructor(private intl: IntlService) {
this.value = this.intl.parseDate("2018-05-01T13:23:35.1229748+04:30");
this.valueString = "2018-05-01T13:23:35.1229748+04:30";
}
}
html
<!-- Works fine -->
<kendo-datepicker
[(value)]="value"
></kendo-datepicker>
<!-- Throws error: The 'value' should be a valid JavaScript Date instance -->
<kendo-datepicker
[(value)]="valueString"
></kendo-datepicker>
You can also find an example of a possible implementation over at KendoUIs documentation (Link)
来源:https://stackoverflow.com/questions/50113771/binding-for-kendo-datepicker-the-value-should-be-a-valid-javascript-date-inst