19

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)]

3 Answers 3

39

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
Sign up to request clarification or add additional context in comments.

4 Comments

Ok, I like this method, but what should the URL in the Ajax call be?
I'm getting: 405 Method Not Allowed
What is the exact url you are sending the request to? I ask because some Googling brought this up: This problem occurs only when you use Microsoft Internet Information Services (IIS) 4.0 and Microsoft Internet Information Services 5.0. This problem occurs if you send a POST request to a server that is running IIS 4.0 or IIS 5.0, and the POST request contains a URL that ends in a slash mark (/). IIS returns the 405 error message instead of the default document. However, if the method value of the Verb property is GET or HEAD, IIS returns the default document.
The MIME media type for JSON text is application/json. The default encoding is UTF-8. (Source: RFC 4627)
4

Yes your method has to be static with the WebMethod attribute

Basic example:

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

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

1 Comment

Wherefrom the d come?
1

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.

 [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}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.