2012-05-18 24 views
7

Próbuję pobrać obiekt JSON na C# tutaj jest mój wpis InitSciprt, ale nie jestem w stanie przekazać go na codebehind, dzięki!JQuery Ajax Post do C#

$.ajax({ 
    type: "POST", 
    url: "facebook/addfriends.aspx", 
    data: { "data": response.data }, 
    contentType: "application/json; charset=utf-8", 
    dataType: "json", 
    success: function (msg) { 
     location = '/facebook/login?URL=' + ReturnURL + '&UID=' + response.authResponse.userID + '&TK=' + response.authResponse.accessToken + ''; 
    } 
}); 

Próbowałem odzyskać dane, takie jak:

Request.Form["data"] 
Request["data"] 
+0

WebForms lub MVC? – jrummell

Odpowiedz

12

Oto przykład z Encosia.com (dodałem parametr formularza). Nie musisz mieć dostępu do Page.Form - możesz zamiast tego używać parametrów metody.

kodzie

public partial class _Default : Page 
{ 
    [WebMethod] 
    public static string GetDate(string someParameter) 
    { 
    return DateTime.Now.ToString(); 
    } 
} 

JavaScript

$(document).ready(function() { 
    // Add the page method call as an onclick handler for the div. 
    $("#Result").click(function() { 
    $.ajax({ 
     type: "POST", 
     url: "Default.aspx/GetDate", 
     data: {someParameter: "some value"}, 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 
     success: function(msg) { 
     // Replace the div's content with the page method's return. 
     $("#Result").text(msg.d); 
     } 
    }); 
    }); 
}); 
+0

Dzięki, ale nie próbuję uzyskać danych z C# do JavaScriptu Próbuję opublikować dane z JavaScript do C# –

+0

Obejmuje to wpis i odpowiedź ... – jrummell

+0

Tak, ale to nie zawiera właściciela danych na codebehind , Myślę, że słowo kluczowe WebMethod wykonuje zadanie? –

2

Tak zrobiłem i pracował dla mnie:

$.ajax({ 
    type: "POST", 
    url: "facebook/addfriends.aspx", 
    data: "data=" + response.data + "&data1=anyothervaluelikethis", 
    contentType: "application/x-www-form-urlencoded", 
    dataType: "json", 
    success: function (msg) { 
     location = '/facebook/login?URL=' + ReturnURL + '&UID=' + response.authResponse.userID + '&TK=' + response.authResponse.accessToken + ''; 
    } 
}); 

Te dwie linie są modyfikowane

data: "data=" + response.data + "&data1=anyothervaluelikethis", 
contentType: "application/x-www-form-urlencoded", 
2

związanym kodzie C# metoda podpis powinien wyglądać mniej więcej tak:

[WebInvoke(UriTemplate = "MyMethod", Method = "POST", ResponseFormat = WebMessageFormat.Json)] 
public Object MyMethod(Object data){ 
// your code 
} 

gdzie obiekt może być dowolny serializable klasa