Skip to main content
 首页 » 编程设计

c#之使用 jquery ajax 调用 C# webmethod 省略可选参数

2024年02月13日35artech

我有一个这样的网络方法:

[WebMethod(EnableSession = true)] 
public string testMethod(string param1, string param2="default value") 
{ 
    ....... 
} 

我正在尝试使用 jquery 调用此方法并忽略可选参数,并且 web 方法没有被命中。

$.ajax({ 
    type: "POST", 
    url: url, 
    data: { "param1": "value1" } 
}).complete(function (data) {....});   

只有当我也传递第二个参数时,我才工作。有什么办法可以解决这个问题吗?

请您参考如下方法:

我认为您不能将可选参数与网络服务方法一起使用,您可能需要重载该方法...

[WebMethod(EnableSession = true, MessageName = "testMethod"))] 
public string testMethod(string param1, string param2) 
{ 
      ....... 
} 
 
[WebMethod(EnableSession = true, MessageName = "testMethod")] 
public string testMethod(string param1) 
{ 
      testMethod(param1, "default value"); 
} 

编辑:文章链接。

还有一个 article here值得一读以了解其他方法,尽管它得出的结论是不使用重载,但我想这是您的决定。