2012-05-18 34 views
7

Tôi đang cố truy xuất đối tượng JSON trên C# đây là bài đăng JavasSciprt của tôi nhưng tôi không thể giao nó trên codebehind, cảm ơn!JQuery Ajax Đăng lên 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 + ''; 
    } 
}); 

tôi đã cố gắng để lấy dữ liệu như:

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

WebForms hoặc MVC? – jrummell

Trả lời

12

Dưới đây là một ví dụ từ Encosia.com (Tôi đã thêm một tham số hình thức). Bạn không cần phải truy cập Page.Form - thay vào đó bạn có thể sử dụng các tham số phương pháp.

codebehind

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

Cảm ơn nhưng tôi không cố gắng lấy dữ liệu từ C# đến Javascipt Tôi đang cố gắng đăng dữ liệu từ JavaScript lên C# –

+0

Điều này bao gồm một bài đăng và phản hồi ... – jrummell

+0

Có nhưng không chứa một trình giữ dữ liệu trên codebehind , Tôi nghĩ rằng từ khóa WebMethod thực hiện công việc? –

2

Đây là cách tôi đã làm và nó làm việc cho tôi:

$.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 + ''; 
    } 
}); 

Hai dòng này được sửa đổi

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

Các codebehind C# phương pháp chữ ký nên giống như thế:

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

nơi đối tượng có thể được bất kỳ lớp serializable

Các vấn đề liên quan