问题
Is it possible to post a DateTime parameter to a Web Method inside an ASMX web service (using a JSON serialized RPC style call)?
I am sending a DateTime to the browser and this gets serialized in the form /Date(1350639464100+0100)/. I can then use the excellent moment.js library to parse the date, display it on the page etc.
My problem is returning this date to the server using an AJAX post to my web service. My web method looks something like this:
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void Save(DateTime date)
{
// Do stuff
}
If I try to send a date in the same format as it came down (/Date(1350639464100+0100)/) then I get an error:
/Date(1350639464100+0100)/ is not a valid value for DateTime.
Are there any better alternatives to sending this up as a string and then parsing the value on the server? Ideally I'd like to be able to send objects on a round trip to and from the server without having to alter any date properties that they may contain.
Thanks for any help!
回答1:
You can change the parameter type to string and then you can convert that string to any type you want
public void Save(String date){
*Code*
}
回答2:
I've got this working now as follows.
Web method using a DateTime parameter:
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void Save(DateTime date)
{
// Do stuff
}
AJAX post to the web method sending dates as strings (in an international format to avoid localisation problems):
{"date": "2012-10-19"}
or, using moment.js:
{"date": moment().format("YYYY-MM-DD HH:mm:ss")}
来源:https://stackoverflow.com/questions/12971672/passing-a-datetime-parameter-to-asp-net-web-service