2011-04-13 2 views
2

나는 다음과 ASP.net 웹 방법이 있습니다jQuery Javascript의 Array 매개 변수로 ASP.net 웹 메서드를 호출하는 방법은 무엇입니까?

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

내가 jQuery를 자바 스크립트 코드에서이 코드를 호출하고있어,하지만 내가 배열을 전달하는 구문을 모른다. 일반적으로 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     
      } 
     }); 

내 의도는 내 웹 메소드에 배열을 전달할 경우 비슷한 스타일로 코드를 작성하는 것입니다 : 여기에 작동합니까 배열없이 코드 의 예입니다.

+0

중복 가능성 (http://stackoverflow.com/questions/7971393/passing 사용해 -array-of-strings-to-webmethod-with-variable-of-arguments-of-jq) – weir

답변

0

사용자는
이 필요합니다. 1) data 매개 변수에 id 및 roles 속성이있는 객체를 할당하십시오.
2) roles 속성에 문자열 배열을 할당합니다.
3) ajax 호출에 옵션을 전달하는 동안 전통적인 설정을 true로 설정하십시오.

예컨대 :의 WebMethod에 PARAM을 전달

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

배열 형식으로 자바 스크립트 코드에 배열이 있습니다. 데이터를 가져 오는 가장 쉬운 방법은 무엇일까 ... 그리고 왜 코드에 'traditional : true'를 추가 했습니까? –

+0

이 코드를 사용하면 다음 오류가 발생합니다. "유효하지 않은 JSON 프리미티브 :"id " –

+0

전통적인 매개 변수가 필요한 경우 http://jquery14.com/day-01/jquery-14#backwards 링크를 확인하십시오. Net – Chandu

2

조금 까다 롭습니다. 이와

[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); 
관련 문제