2011-04-13 54 views
2

我有以下ASP.net Web方法:如何使用jQuery Javascript中的数组参数调用ASP.net web方法?

[WebMethod] 
public static string SaveUserNew(string id, string[] roles) 
{ 
doStuff(id, roles); 
} 

我打电话从jQuery的Javascript代码的代码,但我不知道传递一个数组的语法。通常情况下,我写jQuery代码来调用网页方法,看起来像这样:

 $.ajax({ 
      type: "POST", 
      url: "someUrl.aspx?webmethod", 
      data: '{"foo":"fooValue"}', 
      contentType: "application/json;", 
      dataType: "json", 
      } 

请阐明这一点。

更新:这里是没有阵列,做工作的代码一个例子:

[WebMethod] 
public static string SaveUserNew(string id) 
{ 
    return "0"; 
} 

     var jdata = '{ "id": "3TWR3"}'; 

     $.ajax({ 
      type: "POST", 
      url: "UserMgmt.aspx/SaveUserNew", 
      data: jdata, 
      contentType: "application/json;", 
      dataType: "json", 
      traditional: true     
      } 
     }); 

我的本意是写一些代码以类似的风格,我传递数组到我的Web方法。

+0

可能重复(http://stackoverflow.com/questions/7971393/passing -array-of-strings-to-webmethod -with-variable-number-of-arguments-using-jq) – weir 2014-06-18 17:17:40

回答

0

您需要
1)将数据参数赋值为具有属性id和角色的对象。
2)为角色属性分配一个字符串数组。
3)将选项传递给ajax调用时,将传统设置设置为true。

e.g:

$.ajax({    
    type: "POST",    
    url: "someUrl.aspx?webmethod",    
    data: { 
     "id":"1", 
     "roles":[ 
      "Admin", 
      "Something", 
      "Another Thing" 
     ] 
    }, 
    contentType: "application/json;",    
    dataType: "json", 
    traditional: true //############################# 
} 
+0

我的数组在我的javascript代码中是一个数组类型。我想知道将数据写入数据的最简单方法是什么......为什么要在代码中添加“traditional:true”? – 2011-04-13 16:18:28

+0

当我使用此代码时,出现以下错误:“无效的JSON基元:”id“ – 2011-04-13 16:23:22

+0

请检查传统参数需要的链接http://jquery14.com/day-01/jquery-14#backwards。 Net – Chandu 2011-04-13 16:23:29

2

传递参数去的webmethod是有点棘手。尝试这一个

[WebMethod] 
public static string GetPrompt(string[] name) 
{ 

    return "Hello " + name[0] + " and " + name[1]; 
} 

的JScript [传递串的阵列的使用jQuery AJAX参数变量数目WEBMETHOD]的

var param = "{'name':['jack', 'jill']}"; 
var option = { 
    error: function(request, status, error) { 
     alert(error); 
    }, 
    cache: false, 
    success: function(data, status) { 
     alert(data.d); 
    }, 
    type: "POST", 
    contentType: "application/json; charset=utf-8", 
    data: param, 
    dataType: "json", 
    url: "../Server/ArrayParam.aspx/GetPrompt" 
}; 

$.ajax(option); 
相关问题