2011-04-13 50 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); 
相關問題