2010-11-22 9 views
9

So che ci sono altre discussioni su questo, ma loro non mi aiutano e sto impazzendo qui!Passaggio di parametri in una chiamata jQuery ajax a un metodo web ASP.NET

Voglio passare alcuni parametri in un metodo Web utilizzando jQuery Ajax.

var paramList = ''; 
for(i = 0; i < IDList.length; i++){ 
    if (paramList.length > 0) paramList += ','; 
     paramList += '"' + 'id' + '":"' + IDList[i].value + '"'; 
    } 
    paramList = '{' + paramList + '}'; 
    var jsonParams = JSON.stringify(paramList); 


    $.ajax({ 
     type: "POST",   
     url: "editactivity.aspx/UpdateSequenceNumber",   
     data: jsonParams, 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 
     success: function(response) { 

     } 
    }); 

Nella chiamata ajax, se ho messo i dati a paramlist ottengo l'errore: "Non valido chiamata di servizio web, valore mancante per il parametro: \ u0027a \ u0027".

Se metto dati jsonParams ottengo l'errore:

"Cannot convert object of type \u0027System.String\u0027 to type \u0027System.Collections.Generic.IDictionary`2[System.String,System.Object]\u0027"

Se scrivo fuori paramList, è in un corretto formato JSON come {"id":"140", "id":"138"}

Se scrivo fuori jsonParams, è in un errato formato come "{\"id\":\"140\",\"id\":\"138\"}"

il metodo web: (non fa più di tanto ancora ..)

[System.Web.Services.WebMethod] 
    public static string UpdateSequenceNumber(string a, string b) 
    { 
     return a+b; 
    } 

Cosa sto sbagliando? Non riesco a ottenere questa cosa JSON giusta.

UPDATE:

Dopo qualche aiuto dalla prima risposta che ora mando {"id":["138","140"]} nella richiesta AJAX.

Il metodo Web ora utilizza una stringa denominata id come parametro.

[System.Web.Services.WebMethod] 
public static string UpdateSequenceNumber(string id) 
{ 
    return id; 
} 

Ora ottengo il nuovo errore:

"Type \u0027System.Array\u0027 is not supported for deserialization of an array."

risposta

14

vostri JSON nomi dei parametri devono essere lo stesso con i nomi C# paramter.

{"a":"140", "b":"138"} 

Se si invia numero imprecisato di parametri ai server, è possibile concat al lato client in un parametro e poi dividere a lato server.

+0

Grazie, non lo sapevo. Subito dopo lo var c = JSON.stringify ({"id": lista}); Ottengo: {"id": ["138", "140"]} che sembra a posto. Ma so che ho un nuovo errore quando faccio la richiesta Ajax: "Type \ u0027System.Array \ u0027 non è supportato per la deserializzazione di un array." – larschanders

+0

Non sapevo che possiamo usare List type come C# datatype con webmethod, grazie;) –

+0

Contento che potremmo aiutarci l'un l'altro :) – larschanders