Daniel A Sathish Kumar Daniel A Sathish Kumar - 1 year ago 117
jQuery Question

Is It possible to use web method in C# class?

I'm using web method in C# class file(i.e not a partial class of any web form) and I have html file. I just want to call web method from html file using JQuery AJAX GET and POST methods. Is it possible to do this? Is this have any sense? or i must want use asp web form?

Answer Source

To answer your question it's important that you first understand the prurpose of having a web service.Web services allow us to expose any piece of software over the internet and allow clients to consume it.

In .NET ASMX web services we expose software to the outside world by decorating methods with the [WebMethod] attribute.But even if we apply the [WebMethod] attribute our method will not be available over the internet unless it's inisde a:

  1. .asmx web service file
  2. .aspx web page

Hopefully now you understand why you can't simply define a [WebMethod] inside a standard C# class.Below is a simple example of calling an ASMX web service from a plain html page:


[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class MyService : System.Web.Services.WebService
    public string GreetUser(string name)
        return String.Format("Hello {0}",name);


    <meta charset="utf-8" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#btnCallService").click(function () {
                    type: "POST",
                    url: "MyService.asmx/GreetUser",
                    contentType: "application/json;charset=utf-8",
                    data: '{name:"' + $("#txtName").val() + '"}',
                    dataType: "json",
                    success: function (data) {
                    error: function (errordata) {
    <input type="text" id="txtName" />
    <input type="button" value="Call Service" id="btnCallService" />
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download