2012-05-18 80 views
7

我想在C#上检索JSON对象,这里是我的JavasSciprt文章,但我无法在代码隐藏上讨论它,谢谢!JQuery Ajax Post to 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 + ''; 
    } 
}); 

我试着像检索数据:

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

的WebForms或MVC? – jrummell

回答

12

下面是Encosia.com一个例子(我加了一个表单参数)。您无需访问Page.Form - 您可以改用方法参数。

代码隐藏

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#到Javascipt的数据我试图从JavaScript发布数据到C# –

+0

这包括一个帖子和一个响应... – jrummell

+0

是的,但没有包含代码隐藏的数据持有者,我认为WebMethod关键字可以完成这项工作吗? –

2

这是我如何做,它的工作对我来说:

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

这两条线被修改

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

代码隐藏的C#方法签名应该是这个样子:

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

这里对象可以是任何序列化类