Daniel A Sathish Kumar Daniel A Sathish Kumar - 3 months ago 20
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

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:

MyService.asmx:

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

Index.html:

<html>
<head>
    <title></title>
    <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 () {
                $.ajax({
                    type: "POST",
                    url: "MyService.asmx/GreetUser",
                    contentType: "application/json;charset=utf-8",
                    data: '{name:"' + $("#txtName").val() + '"}',
                    dataType: "json",
                    success: function (data) {
                        alert(data.d);
                    },
                    error: function (errordata) {
                        console.log(errordata);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <input type="text" id="txtName" />
    <input type="button" value="Call Service" id="btnCallService" />
</body>
</html>