2012-03-08 63 views
0

我創建一個投票以下JSON對象發佈JSON對象到WebService和處理它有

$("#btnSubmit").click(function() { 
    var poll = { 'q': $('#txtQuestion').val(), 'a': [] }; 

    for (i = 1; i < counter; i++) { 
     var a = $('#txtAnswer_' + i).val(); 
     poll.a.push(a); 
    } 


        $.ajax({ 
         type: 'POST', 
         url: "../_ws/Polls.asmx", 
         data: JSON.stringify(poll), 
         contentType: 'application/json; charset=utf-8', 
         dataType: 'json' 

        }); 



}); 

基本上,這retreives一個問題文本框的值和答案文本框(動態創建)。結果是一個'民意調查'對象。

我想發送這個對象到一個web服務,如上所示。直到這裏沒有問題。我的問題是如何檢索這個json對象並在我的web服務中的函數中處理它?

<WebMethod()> _ 
<ScriptMethod()> 
Public Function AddPoll(**??? as ???**) As String 

End Function 

如果有人能幫上忙,我將不勝感激。

+0

您正在使用哪個版本的.NET? – 2012-03-08 20:53:37

+0

我正在使用4.0版本 – 2012-03-08 20:54:52

回答

0

如果我理解正確,poll最終會看起來像這樣?

{ q: 'Question text', a: [ 'Answer 1', 'Answer 2', 'Answer 3' ] } 

如果是這樣,你可以用一個簡單的方法聲明會是這樣的:

Public Function AddPoll(q as String, a as List<string>) 

如果你想要的東西更精確,你可以建立自己的一套匹配類型:

public class PollDTO { 
    public string q { get; set; } 
    public List<string> a { get; set; } 
} 

<WebMethod()> 
Public Function AddPoll(pollData as PollDTO) 

你需要你的jQuery的數據參數也更改爲組單變量也在數據:

data: JSON.stringify({ pollData: poll }) 

更多關於此處:http://encosia.com/using-complex-types-to-make-calling-services-less-complex/

+0

推特,​​谷歌搜索,現在在這裏。我在網上讀到關於你和你的帖子的消息比我每天看到我母親的時間多:))非常感謝你! – 2012-03-08 22:01:13

+0

@Emin沒問題。很高興我能幫上忙。 – 2012-03-08 22:27:44