2012년 11월 12일 월요일

How to use JQuery to call a WebService (*.asmx) method?


Introduction

This article will provide a short introduction of using Jquery to call a method from a webservice.

Jquery Ajax to a WebService method

1. Add a WebService to your project. Rightclick on your project "Add -> New Item" and add a new Web Service to the project:

Add Webservice

2. Replace the class definition with this one:
1
2
3
4
5
6
7
8
9
10
11
12
13
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
 [System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
 
    [WebMethod]
    public string TestMethod(String data)
    {
        return data;
    }
}

3. Add a new "Web Form" to the project
Add Webform
and replace the HTML content with
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head id="Head1" runat="server">
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript">
        function serviceCall() {
            $.ajax({
                type: "POST",
                url: 'WebService1.asmx/TestMethod',
                data: "{'data':'This is static data from the JavaScript file'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    $("#divResult").html(msg.d);
                },
                error: function (e) {
                    $("#divResult").html("WebSerivce unreachable");
                }
            });
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div style="width: 100px; height: 30px; background-color:yellow;" onclick="serviceCall();">Click me</div>
    <div id="divResult" style="margin-top: 20px;"></div>
    </form>
</body>
</html>

4. Run the project, open your web form and click on the yellow div.
(That's all you need to do if you are using .net 4.0 (in previous versions you may need to add a ScriptHandler to your web.config)  and no IIS 7.5 Urlrewriting module (see the warning at the end of the article)).
The result will be:
Result 1


 

Jquery Ajax to a WebService method with parametes from a TextBox

So far we only used static content in the JavaScript file, which is not very useful.
Let's add a TextBox to our html:
1
<asp:TextBox ID="txtInput" runat="server" />

Because the TextBox has the runat="server" attribute, the id of the TextBox usually starts with a longer prefix. To address that, we use JQuery to get a reference to the TextBox.
To add a little more complexity, let's also assume that the yellow button should only perform the Ajax call, if the TextBox is not empty.

JavaScript:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<script type="text/javascript">
    function serviceCall() {
        var txtInput = $("#<%=txtInput.ClientID%>").val();
        if (txtInput.length > 0) {
            $.ajax({
                type: "POST",
                url: 'WebService1.asmx/TestMethod',
                data: "{'data':'" + txtInput + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    $("#divResult").html(msg.d);
                },
                error: function (e) {
                    $("#divResult").html("WebSerivce unreachable");
                }
            });
        }
    }
</script>


Result
Jquery call 2

Complete HTML:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head id="Head1" runat="server">
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript">
        function serviceCall() {
            var txtInput = $("#<%=txtInput.ClientID%>").val();
            if (txtInput.length > 0) {
                $.ajax({
                    type: "POST",
                    url: 'WebService1.asmx/TestMethod',
                    data: "{'data':'" + txtInput + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {
                        $("#divResult").html(msg.d);
                    },
                    error: function (e) {
                        $("#divResult").html("WebSerivce unreachable");
                    }
                });
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div style="width: 100px; height: 30px; background-color: yellow;" onclick="serviceCall();">
        Click me</div>
    <asp:TextBox ID="txtInput" runat="server" />
    <div id="divResult" style="margin-top: 20px;">
    </div>
    </form>
</body>
</html>

Warning

If you are using the UrlRewrite 2 Module for IIS 7.5, you need be careful with the LowerCaseRule. In my case, I spend hours trying to figure out, why my method wasn't called. It turned out to be, that I used PascalCase for the naming of my method, but the method was never called because the UrlRewrite Module changed the casing:
1
2
3
4
<rule name="LowerCaseRule1" stopProcessing="true">
    <match url="[A-Z]" ignoreCase="false" />
    <action type="Redirect" url="{ToLower:{URL}}" />
</rule>
Change these lines into:
1
2
3
4
5
6
7
<rule name="LowerCaseRule1" stopProcessing="true">
    <match url="[A-Z]" ignoreCase="false" />
    <conditions>
        <add input="{URL}" matchType="Pattern" pattern="^.+\.((axd)|(js)|(xaml)|(asmx))$" ignoreCase="true" negate="true"/>
    </conditions>
    <action type="Redirect" url="{ToLower:{URL}}" />
</rule>
I hope this warning will be indexed by google, that it may later be found by someone else.

댓글 없음: