【问题标题】:ASP.NET WebMethod for Ajax not accepting date form "dd/MM/yyyy"用于 Ajax 的 ASP.NET WebMethod 不接受日期形式“dd/MM/yyyy”
【发布时间】:2017-08-30 10:22:13
【问题描述】:

在我的一个 ASP.NET 项目中,我使用带有一些参数的 jQuery ajax 请求来请求数据。其中之一是日期参数,格式为 'dd/MM/yyyy'

$.ajax({
    type: "POST",
    url: "somePath/xyzMethod",
    data: "{'param1': 'a', 'date': '31/08/2017'}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    async:true,// false,
    success: functions(response) { }  
});

在我的 .vb 文件中,我有以下用于上述 ajax 调用的 WebMethod:

<WebMethod(EnableSession:=True)>
Public Shared Function xyzMethod(ByVal param1 As String, Byval date as 
DateTime)

//End Function

当进行 ajax 调用时,我收到以下错误:

{Message: "30/08/2017 is not a valid value for DateTime.",…}
ExceptionType
:
"System.FormatException"
Message
:
"30/08/2017 is not a valid value for DateTime."
StackTrace
:
"   at System.ComponentModel.DateTimeConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
↵   at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeInternal(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject)
↵   at System.Web.Script.Services.WebServiceMethodData.StrongTypeParameters(IDictionary`2 rawParams)
↵   at System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext context, WebServiceMethodData methodData, IDictionary`2 rawParams)
↵   at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)"

【问题讨论】:

  • 将其更改为字符串并将方法中的字符串值转换为 DateTime。

标签: jquery asp.net vb.net date


【解决方案1】:

首先发给WebMethod的参数和WebMethod的参数不匹配:

param1 - p1
日期 - 日期

如果您将 ajax 数据设置为:

data: "{'param1': 'a', 'date1': '31/08/2017'}"

将您的日期参数从DateTime 更改为String,然后这个VB 代码应该可以工作:

<WebMethod(EnableSession:=True)>
Public Shared Function xyzMethod(ByVal param1 As String, ByVal date1 As String)
    Dim convertedDate As DateTime = Convert.ToDateTime(date1)
    'Return what you need
    Return Nothing
End Function

注意:如果我将 WebMethod 的日期参数设置为date,则会出现以下错误:

关键字作为标识符无效。

【讨论】:

  • 查看我的更新。您是否尝试将 WebMethod 参数从 DateTime 更改为 String
猜你喜欢
  • 1970-01-01
  • 2016-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-29
  • 1970-01-01
相关资源
最近更新 更多