如何在ASP.NET Web窗体中获取JSON POST数据? [英] How to get JSON POST data in ASP.NET Web Forms?

查看:911
本文介绍了如何在ASP.NET Web窗体中获取JSON POST数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一些jquery正在将数据发布到我的一个网页上.

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

现在,我只是想让它发布一些JSON以对其进行测试,但我不知道发布后必须在后端实际获取数据.

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.

我一直使用Request.Params来获取发布的数据,但是这次似乎不起作用.

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

这是我用来撰写帖子的代码:

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
});

不过,该帖子绝对是成功的,因为我可以使用Fiddler看到它,另外,当我检查Request.ContentLength时,它会返回正确的发布字节数.

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

但是我找不到任何地方的实际数据. 关于我在做什么错的任何想法吗?

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

谢谢.

推荐答案

发布javascript对象:

  1. 将普通对象传递给data选项,
  2. 单独保留contentType选项.默认选项是完美的.

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

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

服务器端:

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

发布Json:

  1. 数据:JSON.stringify(person),
  2. contentType:"application/json"

服务器端:

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

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

这篇关于如何在ASP.NET Web窗体中获取JSON POST数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆