c# - 使用 jquery ajax 调用 ASP.NET 静态方法中的输入流来发布表单值

标签 c# jquery asp.net ajax

尝试使用 this code

我已经走到了死胡同 在客户端,表单值被收集和序列化,但由于不可能在静态方法中使用请求实例 我未能在服务器上收到序列化表单值, 我尝试使用静态 HttpContext.Current.Request.InputStream 绕过它 但我得到了空流。 我如何获取服务器中的输入流? 客户端:

 function myFunction() {
             $.ajax({
             type: "POST",
             url: "ajaxForm.aspx/Receiver",
             contentType: "application/json; charset=utf-8",
             data: $('#myForm').serialize(),
             datatype : "json",
             cache: false,
             success: function (data) {
                 $('#result').html(data);
             },
             error: function (data) {
                 alert('failed');
             }
         });
     }

服务器端第一个版本(从该链接复制):

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

第二个版本:

  [WebMethod ]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static void  Receiver()
{
    if (HttpContext.Current.Request.InputStream.Position != 0)
    {
                 HttpContext.Current.Request.InputStream.Seek(0,System.IO.SeekOrigin.Begin);
    }
    byte[] data = new byte[HttpContext.Current.Request.InputStream.Length];
    HttpContext.Current.Request.InputStream.Read(data, 0, data.Length);}

最佳答案

目前您的数据看起来不像 JSON。尝试这样。

var jsonData = JSON.stringify({
    form: $('#myForm').serialize()
});

在ajax调用数据

...
contentType: "application/json; charset=utf-8",
             data: jsonData,
             datatype : "json",
...

你的方法:

[WebMethod ]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static void  Receiver(string form)
{
     //in the string form you should have myForm serialize.
}

如果你想使用 Context.Session 来做某事,你需要启用它。

[System.Web.Services.WebMethod(EnableSession = true)]

关于c# - 使用 jquery ajax 调用 ASP.NET 静态方法中的输入流来发布表单值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34917965/

相关文章:

c# - 具有多态数组的 WCF 客户端调用方法失败

c# - MVC 4 默认参数值

javascript - 如何禁用第 3 方引入的 JavaScript 事件处理程序?

asp.net - 使用 JQuery 在 GridView ASP.NET 中选择所有复选框

c# - C# 中的简单 3D 渲染

条件语句中的 C# 6.0 空运算符

c# - 在 C# 中获取域 LogonServer

javascript - 是否可以以不同的形式共享一键点击?

javascript - 类问题css

jquery - CSS Overlay - 叠加层位于弹出窗口之上