简体   繁体   中英

Parse DateTime? format from ajax to asp.net mvc controller

I would like to parse DateTime? from ajax to asp.net mvc controller.

I have following code, where @Model.DateA and @Model.DateB is in DateTime? class. The error i got is uncaught syntax error: unexpected number

[HttpPost]
public class CheckDate(DateTime? datea, DateTime? dateb)
{
}

$.ajax({
  ...
  data: {'datea': @Model.DateA, 'dateb': @Model.DateB }
  ....
});

Use Moment.js. Moment is prepared to deal with almost every date-format passed to it: ASP.NET JSON Dates, String Dates, UNIX, ISO, etc. In this example i'm using Knockout just to show you the output...

//Here you can do this
//var datea = '@Model.DateA.toString()';
//var dateb = '@Model.DateB.toString()';

var datea = "01/23/2015 15:00:00.000";
var dateb = "01/24/2015 15:00:00.000";


//Knockout just to show you date
function MainViewModel(){

    var self = this;

    //Here i pass to moment.js the date, and format it
    //year-month-day; this way is standard for every country
    self.datea = ko.observable(moment(datea).format('YYYY-MM-DD'));
    self.dateb = ko.observable(moment(dateb).format('YYYY-MM-DD'));



    self.sendData = function(){
        var request = $.ajax({
            url: "/CheckDate", //Your controller method
            type: "POST",
            data: { datea : self.datea(), dateb: self.dateb() } //Send date values
        });

        request.done(function(data){
            //Do something with the response...
        });

    };
}
var vm = new MainViewModel();
ko.applyBindings(vm);

For your CheckDate() you are using a class, maybe you want to use JsonResult and send the return with JSON. Something like this:

public JsonResult CheckDate(DateTime? datea, DateTime? dateb){
    //Check dates   
    return Json("OK", JsonRequestBehavior.AllowGet);
}

That might solve your problem. Greetings.

Ah!... JSBIN working

首先将其转换为字符串:

@Model.DateA.Value.ToString("MM-dd-yyyy")

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