aravind
aravind

Reputation: 1096

How to call C# method in jQuery?

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

Upvotes: 2

Views: 46648

Answers (3)

Sid M
Sid M

Reputation: 4354

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" />

Upvotes: 2

Saranya
Saranya

Reputation: 2008

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.

Upvotes: 5

Joe Enos
Joe Enos

Reputation: 40383

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

Upvotes: 1

Related Questions