简体   繁体   中英

To execute the AJAX call to ASP.NET WEb Application

Below is my code in code behind in ASP.NET Web Application

public string GetData(string name)
    {
        WCF_Web_Service.Service1 client = new WCF_Web_Service.Service1();
        string Name=client.GetData(name);
        return Name;
    }

Here I have consumed my simple WCF Service should hive output as Hello,

and below is the my jquery code

function asyncServerCall(name) {
        jQuery.ajax({
            url: 'WebForm1.aspx/GetData',
            type: "POST",
            data: "{'name':" + name + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                alert(data.d);
            }
        });
    }

I have called this function in click event of button as follows

<input type="button" value="click me" onclick="asyncServerCall(1);" />,

I wanted to make AJAX call to call this method from WCF Service, when I click button I get following error

Failed to load resource: the server responded with a status of 500 (Internal Server Error) 

I am novice to use WCF Service and to make AJAx call to evoke its method, any help will be greatly appreciated....

Your GetData method needs to be a static web method, so change it to this.

[System.Web.Services.WebMethod]
public static string GetData(string name)
{
    WCF_Web_Service.Service1 client = new WCF_Web_Service.Service1();
    string Name=client.GetData(name);
    return Name;
}

Here's a good article on the why's but essentially it's because:

This is exactly why they must be marked as static. They cannot interact with the instance properties and methods of your Page class, because a page method call creates no instance of the Page or any of its controls.

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