Passing a DateTime parameter to ASP.NET Web Service

大城市里の小女人 提交于 2019-12-10 22:52:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!