jQuery 如何在 ASP.NET Web Forms 中获取 JSON POST 数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29175594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:34:06  来源:igfitidea点击:

How to get JSON POST data in ASP.NET Web Forms?

jqueryasp.netjsonpostwebforms

提问by Jeremy

I currently have some jquery that is POSTing data onto one of my web pages.

我目前有一些 jquery 正在将数据发布到我的网页之一。

Right now I'm just trying to get it to post some JSON to test it out, but I can't figure out have to actually get the data in my back-end once it's posted.

现在我只是想让它发布一些 JSON 来测试它,但我无法弄清楚一旦发布后必须在我的后端实际获取数据。

I've always used Request.Paramsto get posted data, but it doesn't seem to be working this time.

我一直习惯于Request.Params获取已发布的数据,但这次似乎不起作用。

This is the code I'm using to do the post:

这是我用来做帖子的代码:

// This data is just for testing purposes, doesn't actually do anything
var person = {
    name: "Bob",
    address: "123 Main St.",
    phone: "555-5555"
}

var jqxhr = $.ajax({
    type: "POST",
    url: "/example/mypage.aspx",
    contentType: 'application/json; charset=utf-8',
    dataType: "json",
    timeout: 0,
    success: function () {
        alert("Success");
    },
    error: function (xhr, status, error) {
        alert(error);
    },
    data: person
});

The post is definitely successful though, as I can see it using Fiddler, plus when I check Request.ContentLengthit returns the right number of bytes that was posted.

不过,该帖子肯定是成功的,因为我可以使用 Fiddler 看到它,而且当我检查Request.ContentLength它时,它返回了正确的发布字节数。

But I can't find the actual data anywhere. Any ideas on what I'm doing wrong?

但我无法在任何地方找到实际数据。关于我做错了什么的任何想法?

Thanks in advance.

提前致谢。

回答by Hasta Tamang

Posting javascript object:

发布javascript对象:

  1. pass the plain object to the data option,
  2. leave the contentType option alone. The default option is perfect.
  1. 将普通对象传递给数据选项,
  2. 保留 contentType 选项。默认选项是完美的。

Then you can access the property values of the object in the Request collection as if you have posted a form.

然后您可以访问 Request 集合中对象的属性值,就像您发布了一个表单一样。

server side:

服务器端:

   string input;
    using(var reader = new StreamReader(Request.InputStream)){
            input = reader.ReadToEnd();
        }

Posting Json:

发布 Json:

  1. data: JSON.stringify(person),
  2. contentType: "application/json"
  1. 数据:JSON.stringify(人),
  2. 内容类型:“应用程序/json”

server side:

服务器端:

string json;
using(var reader = new StreamReader(Request.InputStream)){
        json = reader.ReadToEnd();
    }
var person = Json.Decode(json);

Referenced from: http://www.mikesdotnetting.com/article/220/posting-data-with-jquery-ajax-in-asp-net-razor-web-pages

引用自:http: //www.mikesdotnetting.com/article/220/posting-data-with-jquery-ajax-in-asp-net-razor-web-pages