jQuery 如何以标准 Web 表单 .Net 返回 JSON 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8072745/
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-27 09:57:46  来源:igfitidea点击:

How to return a JSON object in standard web forms .Net

jqueryasp.netajaxjsonwebforms

提问by Bj?rn Andersson

The objective is to call a method which does it's thing then returns a JSON object.

目标是调用一个方法,然后返回一个 JSON 对象。

I'm new to JSON.

我是 JSON 的新手。

I have a default.aspx and in it the following code. Now I want an ordinary method in Default.aspx.cs to run on the click event here.

我有一个 default.aspx,其中包含以下代码。现在我想要在 Default.aspx.cs 中的一个普通方法在点击事件上运行。

$(".day").click(function (event) {
var day = $(event.currentTarget).attr('id');
if (day != "") {
    $.ajax(
    {
        type: "POST",
        async: true,
        url: 'Default.aspx?day=' + day,
        data: day,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            console.log("SUCCESS:" + msg);
            //  $(".stripp img").attr('src', "data:image/jpg;" + msg);
            //  $(".stripp").show();
        },
        error: function (msg) {
            console.log("error:" + msg);
        }
    });
}

});

});

Default.aspx.cs looks similar to this:

Default.aspx.cs 看起来类似于:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["day"] != null)
            GetFile(Request.QueryString["day"]);
    }
    public string GetFile(string day)
    {
        string json = "";
        byte[] bytes = getByteArray();

        json = JsonConvert.SerializeObject(bytes);
        return json;
    }

Where am I going wrong here? Should I be using this in some way or is it only applicable in Web Services?

我哪里出错了?我应该以某种方式使用它还是只适用于 Web 服务?

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]

回答by Shai Cohen

I would suggest an HttpHandler. No page lifecycle (so it is blazing fast) and much cleaner code-separation, as well as reusability.

我会建议一个HttpHandler. 没有页面生命周期(所以它非常快)和更清晰的代码分离,以及可重用性。

Add a new item to your project of type "Generic Handler". This will create a new .ashx file. The main method of any class that implements IHttpHandleris ProcessRequest. So to use the code from your original question:

向“通用处理程序”类型的项目添加一个新项目。这将创建一个新的 .ashx 文件。任何实现的类的主要方法IHttpHandlerProcessRequest. 因此,要使用原始问题中的代码:

public void ProcessRequest (HttpContext context) {

    if(String.IsNullOrEmpty(context.Request["day"]))
    {
        context.Response.End(); 
    }

    string json = "";
    byte[] bytes = getByteArray();

    json = JsonConvert.SerializeObject(bytes);
    context.Response.ContentType = "text/json";
    context.Response.Write(json);
}

Change the url in your AJAX call and that should do it. The JavaScript would look like this , where GetFileHandler.ashxis the name of the IHttpHandler you just created:

更改 AJAX 调用中的 url 就可以了。JavaScript 看起来像这样,其中GetFileHandler.ashx是您刚刚创建的 IHttpHandler 的名称:

$.ajax(
    {
        type: "POST",
        async: true,
        url: 'Handlers/GetFileHandler.ashx',
        data: "Day=" + $.toJSON(day),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            console.log("SUCCESS:" + msg);
        },
        error: function (msg) {
            console.log("error:" + msg);
        }
    });

Another small point to consider, if you need access to the Session object from within the Handler code itself, make sure to inherit from the IRequiresSessionStateinterface:

另一个需要考虑的小点,如果您需要从 Handler 代码本身访问 Session 对象,请确保从IRequiresSessionState接口继承:

public class GetFileHandler : IHttpHandler, IRequiresSessionState

回答by GerjanOnline

Yes your method has to be static with the WebMethod attribute

是的,您的方法必须是具有 WebMethod 属性的静态方法

Basic example:

基本示例:

CS

CS

using System;
using System.Web.Services;

public partial class _Default : System.Web.UI.Page
{
  [WebMethod(EnableSession=false)]
  public static string HelloWorld()
  {
    return "Hello World";
  }
}

Javascript

Javascript

<script>
    $.ajax({
      type: "POST",
      url: "Default.aspx/HelloWorld",
      data: "{}",
      contentType: "application/json",
      dataType: "json",
      success: function(msg) {
        console.log(msg.d);
      }
    });
</script>

回答by Martin Larsson

Been a while since I worked with webforms, but if remember correctly it should work if you put the webmethod attribute over GetFile method and make that method static.

自从我使用 webforms 以来已经有一段时间了,但是如果没记错的话,如果您将 webmethod 属性放在 GetFile 方法上并将该方法设为静态,它应该可以工作。

 [WebMethod]
 public static string GetFile(string day)

Furthermore, how you post data in ajax method is a bit off. Remove querystring day from url and data should be in json format, something like {"day":day}

此外,您在 ajax 方法中发布数据的方式有点偏离。从 url 中删除 querystring day,数据应该是 json 格式,类似于 {"day":day}