jQuery AJAX调用将数据发布到ASP.Net页面(不是Get但是POST)

时间:2021-11-04 01:49:13

I have the following jQuery AJAX call to an ASP.Net page.

我有一个ASP.Net页面的以下jQuery AJAX调用。

             $.ajax({
                async: true,
                type: "POST",
                url: "DocSummaryDataAsync.aspx", //"DocSummary.aspx/GetSummaryByProgramCount",
                contentType: "application/json; charset=utf-8",
                data: kendo.stringify({ vendorId: supplierId, businessUnit: busUnit, productSegmentId: prodSegmentId, programId: progId, productManagerId: prodManagerId, companyIds: compIds, expired: exp.toString(), requestType: 'TotalCount' }),
                success: function (msg) {
                    // alert('in success of getcount');

                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    // alert('in failure of getcount');


                }
            });

When I try to retrieve from Request object, the posted data, it does not show up. My aspx page code is as below. I am sending each of posted data in Json format to the page, yet it doesn't show up in code-behind of page. Is there some extra setting in jQuery ajax call that I am missing?

当我尝试从Request对象中检索已发布的数据时,它不会显示出来。我的aspx页面代码如下。我将每个以Json格式发布的数据发送到页面,但它不会显示在页面的代码隐藏中。在jQuery ajax调用中是否有一些额外的设置,我错过了?

   protected void Page_Load(object sender, EventArgs e)
    {
        Response.ContentType = "application/json";

        string requestType = Request.Params["requestType"];


        //populate variables from posted data
        string vendorId = Request.Params["vendorId"];
        string businessUnit = Request.Params["businessUnit"];
        string productSegmentId = Request.Params["productSegmentId"];
        string commitmentProgramId = Request.Params["programId"];
        string productManagerId = Request.Params["productManagerId"];
        string companyIds = Request.Params["companyIds"];
        string expired = Request.Params["expired"];
     }

UPDATE 1: Stephen's answer is the best approach to this, especially the approach that does ProcessRequest. However, I did find a small trick that will allow data to be posted to ASP.Net in the usual traditional manner i.e. like Request["vendorId"] etc. To enable such posting of data from any jQuery ajax request, you simply need to make sure that the following 2 points are applied to your jQuery ajax call:

更新1:Stephen的答案是最好的方法,特别是ProcessRequest的方法。但是,我确实发现了一个小技巧,允许以通常的传统方式将数据发布到ASP.Net,例如Request [“vendorId”]等。要从任何jQuery ajax请求启用此类数据发布,您只需要确保以下2点适用于您的jQuery ajax调用:

  1. The content-type should be left out of your jQuery ajax call Or if you want to include it then it should not be set to "application/json; charset=utf-8" but to "application/x-www-form-urlencoded; charset=UTF-8". Content-type, as per my understanding is telling the ASP.Net page the type of data that is being sent, and not the type of data that is expected of the page.
  2. 内容类型应该从你的jQuery ajax调用中省略或者如果你想要包含它,那么它不应该被设置为“application / json; charset = utf-8”而是应用于“application / x-www-form-urlencoded” ; charset = UTF-8“。根据我的理解,内容类型告诉ASP.Net页面正在发送的数据类型,而不是页面所需的数据类型。
  3. The data part of jQuery ajax should not have the data names enclosed in quotes. So data: {"venorId":"AD231","businessUnit":"123"} should be replaced by data: {vendorId:"AD231",businessUnit:"123"}. In this example the data names are vendorId and businessUnit, which can be accessed in your ASP.Net code-behind using usual ASP.Net syntax like Request["vendorId"] and Request["businessUnit"].
  4. jQuery ajax的数据部分不应该用引号括起来的数据名。所以数据:{“venorId”:“AD231”,“businessUnit”:“123”}应该被数据替换:{vendorId:“AD231”,businessUnit:“123”}。在此示例中,数据名称为vendorId和businessUnit,可以使用常用的ASP.Net语法(如Request [“vendorId”]和Request [“businessUnit”]在ASP.Net代码隐藏中访问)。

1 个解决方案

#1


30  

Option 1. Keep your server side code the same

选项1.保持服务器端代码相同

First remove the kendo.stringify. Then either remove the contentType or change it to...

首先删除kendo.stringify。然后删除contentType或将其更改为...

"application/x-www-form-urlencoded; charset=utf-8" 

...or change your $.ajax call to this:

...或者将$ .ajax调用更改为:

$.post('DocSummaryDataAsync.aspx', { vendorId: supplierId, businessUnit: busUnit, productSegmentId: prodSegmentId, programId: progId, productManagerId: prodManagerId, companyIds: compIds, expired: exp.toString(), requestType: 'TotalCount' }, function (data) { });

Option 2. Change the POST to GET

选项2.将POST更改为GET

Like this

喜欢这个

$.ajax({
async: true,
type: "GET",
etc.

This will pass your data via the QueryString. If you remove the kendo.stringify call you would access all the values like this:

这将通过QueryString传递您的数据。如果你删除了kendo.stringify调用,你将访问所有的值,如下所示:

string vendorId = Request.QueryString[0];
string businessUnit = Request.QueryString[1];
etc.

Option 3. Use your original $.ajax call

选项3.使用原始的$ .ajax调用

If you use your original $.ajax, then the following applies:

如果您使用原始的$ .ajax,则以下内容适用:

Request.Params gets a "combined collection of QueryString, Form, Cookies, and ServerVariables items." - this link

Request.Params获得“QueryString,Form,Cookies和ServerVariables项目的组合集合”。 - 这个链接

You are not working with any of those. Instead, you need to access Request.InputStream.

你没有使用任何这些。相反,您需要访问Request.InputStream。

Here's how you can do that:

这是你如何做到这一点:

Create a class on the server side which maps to the requested JSON object, e.g.

在服务器端创建一个映射到请求的JSON对象的类,例如

public class MyClass
{
    // The type (int or string) should probably correspond to the JSON
    public int vendorId { get; set; }
    public string businessUnit { get; set; }
    public string productSegmentId { get; set; }
    public string programId { get; set; }
    public string productManagerId { get; set; }
    public string companyIds { get; set; }
    public string expired { get; set; }
    public string requestType { get; set; }
}

Convert Request.InputStream into that type, and then you can use it.

将Request.InputStream转换为该类型,然后您可以使用它。

public void ProcessRequest()
{
    System.IO.Stream body = Request.InputStream;
    System.Text.Encoding encoding = Request.ContentEncoding;
    System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding);
    string json = reader.ReadToEnd();
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    MyClass myclass = (MyClass)serializer.Deserialize(json, typeof(MyClass));
    int vendorId = myclass.vendorId;
    string requestType = myclass.requestType;
    // etc...
}

protected void Page_Load(object sender, EventArgs e)
{
    ProcessRequest();
}

#1


30  

Option 1. Keep your server side code the same

选项1.保持服务器端代码相同

First remove the kendo.stringify. Then either remove the contentType or change it to...

首先删除kendo.stringify。然后删除contentType或将其更改为...

"application/x-www-form-urlencoded; charset=utf-8" 

...or change your $.ajax call to this:

...或者将$ .ajax调用更改为:

$.post('DocSummaryDataAsync.aspx', { vendorId: supplierId, businessUnit: busUnit, productSegmentId: prodSegmentId, programId: progId, productManagerId: prodManagerId, companyIds: compIds, expired: exp.toString(), requestType: 'TotalCount' }, function (data) { });

Option 2. Change the POST to GET

选项2.将POST更改为GET

Like this

喜欢这个

$.ajax({
async: true,
type: "GET",
etc.

This will pass your data via the QueryString. If you remove the kendo.stringify call you would access all the values like this:

这将通过QueryString传递您的数据。如果你删除了kendo.stringify调用,你将访问所有的值,如下所示:

string vendorId = Request.QueryString[0];
string businessUnit = Request.QueryString[1];
etc.

Option 3. Use your original $.ajax call

选项3.使用原始的$ .ajax调用

If you use your original $.ajax, then the following applies:

如果您使用原始的$ .ajax,则以下内容适用:

Request.Params gets a "combined collection of QueryString, Form, Cookies, and ServerVariables items." - this link

Request.Params获得“QueryString,Form,Cookies和ServerVariables项目的组合集合”。 - 这个链接

You are not working with any of those. Instead, you need to access Request.InputStream.

你没有使用任何这些。相反,您需要访问Request.InputStream。

Here's how you can do that:

这是你如何做到这一点:

Create a class on the server side which maps to the requested JSON object, e.g.

在服务器端创建一个映射到请求的JSON对象的类,例如

public class MyClass
{
    // The type (int or string) should probably correspond to the JSON
    public int vendorId { get; set; }
    public string businessUnit { get; set; }
    public string productSegmentId { get; set; }
    public string programId { get; set; }
    public string productManagerId { get; set; }
    public string companyIds { get; set; }
    public string expired { get; set; }
    public string requestType { get; set; }
}

Convert Request.InputStream into that type, and then you can use it.

将Request.InputStream转换为该类型,然后您可以使用它。

public void ProcessRequest()
{
    System.IO.Stream body = Request.InputStream;
    System.Text.Encoding encoding = Request.ContentEncoding;
    System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding);
    string json = reader.ReadToEnd();
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    MyClass myclass = (MyClass)serializer.Deserialize(json, typeof(MyClass));
    int vendorId = myclass.vendorId;
    string requestType = myclass.requestType;
    // etc...
}

protected void Page_Load(object sender, EventArgs e)
{
    ProcessRequest();
}