2

I am using a chart which should get Input from C# for plotting the graph. I am using JSON for returning the values from C# to jQuery. Anyhow it doesn't help me, what did I do wrong?

This is my aspx code:

<script type="text/javascript">
    $(document).ready(function () {
        var source = {};

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: "Default.aspx/getall",
            contentType: 'application/json; charset=utf-8',
            cache: false,
            success: function (response) {

                source = $.parseJSON(response.d);

            },
            error: function (err) {
                alert('Error');
            }
        });
</script>

And this is my C# code:

public class sampledata
{
    public string Day { get; set; }
    public int Keith { get; set; }
    public int Erica { get; set; }
    public int George { get; set; }
}

public partial class _Default : System.Web.UI.Page 
{
    List<sampledata> s = new List<sampledata>();

    protected void Page_Load(object sender, EventArgs e)
    {
        s.Add(new sampledata { Day = "monday", Keith = 20, Erica = 15, George = 25 });
        s.Add(new sampledata { Day = "tuesday", Keith = 25, Erica = 20, George = 35 });

        Session["data"] = s;                  
    }

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static List<sampledata> getall()
    {
        List<sampledata> data = (List<sampledata>)HttpContext.Current.Session["data"];
        return data;
    }
}
3
  • Did you try console.log(response) in success? Commented Oct 31, 2013 at 8:36
  • I think you are calling this method as a webservice. you need to add web service to call getall Commented Oct 31, 2013 at 8:46
  • msdn.microsoft.com/en-us/library/… Commented Oct 31, 2013 at 8:46

3 Answers 3

5

I tested your code and everything seems to be fine, except that I serialized the List into a string and returned.

$(window).load(function () {
    $.ajax({
        type: "POST",
        url: "PageMethodTest.aspx/getall",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: fnsuccesscallback,
        error: fnerrorcallback
    });
});

function btnclick() {}

function fnsuccesscallback(data) {
    alert(data.d);

}

function fnerrorcallback(result) {
    alert(result.statusText);
}

Server side code:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static String getall()
{
    List<sampledata> data = (List<sampledata>)HttpContext.Current.Session["data"];
    JavaScriptSerializer js = new JavaScriptSerializer();

    return js.Serialize(data);
    //return data;
}

And the result is:

enter image description here

You can improve on using the output as source for your graph.

Sign up to request clarification or add additional context in comments.

Comments

2

Instead of ajax postback, you can use PageMethods:

In C# page:

[WebMethod]
public static List<sampledata> getall()
{
    List<sampledata> data = (List<sampledata>)HttpContext.Current.Session["data"];
    return data;
}

In the aspx page:

$(document).ready(function () {
    var data=PageMethods.getall(OnSuccess);

    function OnSuccess() {
        alert("Success");
    }
});

And for using PageMethods you also need to add this in your form tag:

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />

Comments

1

If you don't want to rely on Microsoft's AJAX implementation (the WebMethodAttribute, ScriptManager, having to worry about that .d property of the response, etc.), you can do nice clean JSON calls using ASHX handlers. You have to do a little bit of work yourself, but you get out from under WebForms's thumb a bit by doing more traditional AJAX.

For your example, the C# piece would be as follows (note the IRequiresSessionState implementation, which makes your session available):

// something.ashx.cs
public class something : IHttpHandler, IRequiresSessionState {
    public void ProcessRequest(HttpContext context) {
        context.Response.ContentType = "application/json";
        context.Response.Write(JsonConvert.SerializeObject(context.Session["data"]));
    }

    public bool IsReusable { get { return false; } }
}

Your javascript call would just be a call to this something.ashx file:

jQuery.ajax({
    url: "something.ashx",
    type: "post",
    dataType: "json"
}).done(function(result) {
    console.log(result);
});

You don't have any POST parameters, but if you did, you'd just have to include them in your call, and read them directly from the Request in your handler:

jQuery.ajax({
    ...
    data: { requestMessage: "Hello!" }
});


public void ProcessRequest(HttpContext context) {
    string requestMessage = context.Request["requestMessage"]; // Hello!
    ...etc...
}

4 Comments

Quick question, I am trying to understand it and not able to figure out what is being returned in .done(function(result))'s result variable.
@CodeIt The done function's parameter is a function which contains the result of the AJAX call, in the type that you asked for. In this example, the dataType field is set to json, which means that jQuery will be smart enough to look at the result from the server, which is in JSON format, and it will convert it to the object that the JSON represents. For example, if your server sends {"name":"John"}, then result will actually be a javascript object {name: "John"}. See the docs for lots of ways to use jQuery AJAX.
Good explanation @Joe Enos. And how the server is supposed to send a json response? I actually found this answer unique and neat, so I am trying to dig deep in it. sorry if I am being nerd.
@CodeIt The server can build the JSON however it wants. In my example in this answer, it's using the JsonConvert.SerializeObject method, which is part of the JSON.NET library, the most common JSON library in .NET, and then it writes the JSON and the content type directly to the response. ASP.NET MVC has a built-in method (the Json method) to write JSON to the response. Other server frameworks will have their own way of doing it - you'd have to look at the docs for PHP or Rails or whatever else, to figure out the best way to do it.

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.