简体   繁体   中英

Calling function in code behind C# from jQuery

I have an asp web application in visual studio 2008. i have jquery-1.10.2.js in a Folder - JavaScriptBase

files in solution 1. Dashboard.aspx 2. JavaScripts/Dashboard.js

I have a jQuery Tab

<li><a href="#tabs-1" id="tab1" runat="server" onclick="GetData(0)">Today</a></li>
<li><a href="#tabs-2" id="tab2" runat="server" onclick="GetData(7)">1-7 days</a></li>
<li><a href="#tabs-3" id="tab3" runat="server" onclick="GetData(30)">30 days</a></li>
<li><a href="#tabs-4" id="tab4" runat="server" onclick="GetData(60)">60 days</a></li>
<li><a href="#tabs-5" id="tab5" runat="server" onclick="GetData(90)">90 days</a></li>
<li><a href="#tabs-6" id="tab6" runat="server" onclick="GetData(180)">180 days</a></li>

The GetData() function is inside Dashboard.js in a folder- JavaScripts

function GetData(ky)
{
var params = "{'days' : '" + ky + "'}";   // if no params need to use "{}"
alert(params);
        $.ajax({
            url: "Dashboard.aspx/getDataByDate",
            type: 'POST',
            data: params,
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            success: function (data, status) {
                loadSuccess(data, status);
            },
            error: function () {
                alert("Oops! It's an Error");
            }
        });

        return false;
}

In my Code behind

public string getDataByDate(string days)
        {
            DataSet ds = new DataSet();
            ds = getPatientVisitCount(DateTime.Today.ToString(), DateTime.Today.ToString()));
            return ds.GetXml();
        }

when i call the function it always go to error function.

How to call the function in the code behind from js file. please help...

EDIT 1

I change my cs code according to Grundy suggestion

[WebMethod()]
public string getDataByDate(string days)
{
DataSet ds = new DataSet();
ds = getPatientVisitCount(DateTime.Today.ToString(), DateTime.Today.ToString()));
return ds.GetXml();
}

still not getting..

Two things I am noticing here, you are returning XML from your code behind method when it needs to be JSON and you might need to know about data.d.

First, you will need the very popular and robust JSON.NET lib for easy serialization of your XML to JSON. I do not think the System.Web.Script.Serialization.JavaScriptSerializer (which you are not using either, I know) is built to handle XML to JSON, so add the JSON.NET library using NUGET and your code behind should be:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static object getDataByDate(string days)
{
    DataSet ds = new DataSet();
    ds = getPatientVisitCount(DateTime.Today.ToString(), DateTime.Today.ToString()));
    string json = Newtonsoft.Json.JsonConvert.SerializeXmlNode(ds.GetXml());
    return json;
}

If you are using .NET 3.5 you need to understand "d" even though you are using a code behind method and not a web service, just to be safe:

"This is the case with all ASMX services JSON serialized through the ASP.NET AJAX Extensions in ASP.NET 3.5. Even if you're only returning a scalar return value, such as a string, int, or boolean, the result will always be enclosed within the “d”." Reference: http://encosia.com/a-breaking-change-between-versions-of-aspnet-ajax/

So, if you are using .NET 3.5 your jQuey.ajax sucess callback implementation needs to be:

loadSuccess(data.d, status);

If you are using .NET 4.0 or greater you do not need to worry about "d".

You should consider moving this implementation to a web service, it will be almost the same code that I have included in my answer. A web service is more appropriate organization of code in a project for ajax calls and web services seem better suited to handle parsing ajax requests and responses then from code behind though the latter is a guess and ASP.NET may handle methods with the WebMethod attribute the exact same way, whether in code behind or in a web service but the organization of code is a good enough reason to implement getDataByDate in a web service instead of code behind because it is not "connected" to your aspx page per se and may need to be called in multiple pages. It is quite easy to implement, just create a services folder, add a new web service, name it whatever you want, copy and paste the same code in my answer into the web service class, remove the keyword static , and change your ajax url to "/services/[yourwebserivcename].asmx/getDataByDate'.

PS, I know my code works in a web service, not so sure about from code behind but it should work.

PSS, since it is a public method, it is more appropriate to Captialize the web method so getDataByDate should be GetDataByDate

try use WebMethod attribute on this (getDataByDate) method

UPDATE

try changing your method like this:

[WebMethod,ScriptMethod(...params if need...)]
public static string getDataByDate(string days)
{
    DataSet ds = new DataSet();
    ds = getPatientVisitCount(DateTime.Today.ToString(), DateTime.Today.ToString()));
    return ds.GetXml();
}

also see ScriptMethod

Instead of

var params = "{'days' : '" + ky + "'}";

use

var params = {};
params.days = ky;

$.ajax({
            url: "Dashboard.aspx/getDataByDate",
            type: 'POST',
            data: JSON.stringify(params),
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            success: function (data, status) {
                loadSuccess(data, status);
            },
            error: function () {
                alert("Oops! It's an Error");
            }
        });

Also make sure that the url path is correct.You can use '../' to come out of the current folder '../Dashboard.aspx/getDataByDate'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM