简体   繁体   中英

How to pass/map Date object from JavaScript to DateTime object in C# MVC controller action through ajax post?

I am posting a JavaScript date object from the client side and receiving it in the C# controller action. In the C# controller action the object is mapped to a C# DateTime object .

But the DateTime object is not getting the exact value from javascript date object.

Its showing DateTime's min value , ie

01-01-0001 12:00:00 AM

Here is my script code:

var laraHistory = {
        HistoryId: historyId,
        CompanyId: companyId,
        ChangedDate: new Date(Date.parse(changedDate)), //here is how i am setting the date
        LaraId: laraId,
        Comments: comments,
        ChangedById: changedById,
        IsDeleted: true
    };
    $.ajax({
        type: "POST",
        url: "/Manage/HideLaraHistory",
        data: JSON.stringify({ companyLaraHistory: laraHistory }),
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        success: function() {
            window.location.reload();
        }
    });
  • Here is my client side breakpoint screen-shot:

在此处输入图片说明

  • Here is my C# controller action screen-shot:

在此处输入图片说明

Here is my ViewModel class:

public class CompanyLaraHistoryViewModel
{
    public int HistoryId { get; set; }
    public int CompanyId { get; set; }
    [Display(Name = "Company Name")]
    public string CompanyName { get; set; }
    [Display(Name = "LARA")]
    public byte LaraId { get; set; }
    public LARA Lara { get; set; }
    [Display(Name = "Changed Date")]
    public DateTime ChangedDate { get; set; }
    public int ChangedById { get; set; }
    [Display(Name = "Comments")]
    public string Comments { get; set; }
    public bool IsDeleted { get; set; }
}

What can be the possible reason for this? Is it that js date objects cannot be mapped to c# datetime objects?

Can anyone give me a solution?

Consider different approach to the problem. In my applications i prefer to send dates or time to server in some constant format.

For example if in JS I have date which is 1-st January 2015, I send it to server in following format YYYY-MM-DD, and then on server I parse it it C#/any_other_language Date object.

It requires using an Client-Server Adapter which is aware of this format. The same I do when I get date from server. I have an Adapter which converts string to JS Date object.

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