JQuery Ajax Post到C#

13

我正在尝试在C#中检索JSON对象,这是我的JavasSciprt发布,但我无法在代码后端处理它,谢谢!

$.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"]
3个回答

18

这是一个来自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);
      }
    });
  });
});

谢谢,但我不是想从C#获取数据到JavaScript,我是想从JavaScript向C#提交数据。 - Kaner TUNCEL
是的,但它在codebehind中不包含数据持有者,我认为WebMethod关键字可以胜任这个工作? - Kaner TUNCEL
你看到 someParameter 方法参数了吗?那就是你的提交数据。 - jrummell
这并不是很有信息量的。一堆代码没有解释。 - VoidKing
点击 Ecosia 链接获取所有详细信息。 - jrummell
显示剩余2条评论

3
这是我所做的,对我很有效:

$.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
}

Object可以是任何可序列化的类。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接