Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

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

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

I'm new to 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.

$(".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:

    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?

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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 IHttpHandler is ProcessRequest. So to use the code from your original question:

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.ashx is the name of the IHttpHandler you just created:

$.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 IRequiresSessionState interface:

public class GetFileHandler : IHttpHandler, IRequiresSessionState

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...