您的位置:首页 > Web前端 > JQuery

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

2012-10-10 16:24 507 查看

http://www.tomot.de/en-us/article/8/asp.net/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:



2. Replace the class definition with this one:

3. Add a new "Web Form" to the project



and replace the HTML content with

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:



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:

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:

Result:



Complete 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:

Change these lines into:

I hope this warning will be indexed by google, that it may later be found by someone else.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: