miércoles, 11 de noviembre de 2009

How can I call a web service in asp.net from jquery

In this article we are going to show how I call web service in asp.net 2.0 and to return a xml document. After creating the service and returning the xml document we go to do the call using the jquery ajax. The code showed in this example is in vb.net.
This is the code of the web service.
You add a web service to your project that should be called Service.

Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Xml
Imports System.Data
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<System.Web.Script.Services.ScriptService()> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class Services
Inherits System.Web.Services.WebService

Dim xmlDoc As New XmlDocument
<Web.Services.WebMethod()> _
Public Function checkuser(Byval UserName as string, Byval Password as string) As XmlDocument
xmlDoc = New XmlDocument
Dim result As String = ""
If UserName = "Pablo" and Password = "12345" then
result = "True"
result = "False"
end if

xmlDoc.LoadXml("<result val='" & result & "'>" & result & "</result>")
Return xmlDoc
Catch ex As Exception
xmlDoc.LoadXml("<result val='False'>False</result>")
Return xmlDoc
End Try

End Function

End Class

This is the code to call web service from jquery
function checkuser(){
var params = 'UserName=Pablo&Password=12345';
var doc;
var result = new Array();
var rtn;

type: "GET",
url: "Services.asmx/CheckUserName",
data: params,
timeout: 30000,
beforeSend: function(xhr){
xhr.setRequestHeader("Content-Length", params.length);

dataType: "xml",
complete: function(xhr, data){

if (xhr.status == 200) {
//este if verifica si el explorador puede utilizar el XMLDOM ActiveX
if (window.ActiveXObject) {
doc = new ActiveXObject("Microsoft.XMLDOM");
doc.async = false;

rtn = doc.text;
result = rtn.split("_")

if (result[0] == 'True') {

alert('good validation');

else {
$('#lblmsg').html('Invalid User Name');

else {
var dat;
dat = xhr.responseText;
//si no soporta XMLDOM ActiveX utiliza un loop de jquery para localizar los valores dentro del documento xml

rtn = $(this).attr("val");
result = rtn.split("_")
if (result[0] == 'True') {

alert('good validation');
else {
$('#lblmsg').html('Invalid User Name');




else {

alert("Service Error!");




Now from any html or aspx page call the function checkuser. In this case I use html control to calling the function

    function btnCallService_onclick() {

<input id="btnCallService" type="Button" value="Call Service" onclick="return btnCallService_onclick()" />

any suggestion leaves a comment.
good luck

No hay comentarios:

Publicar un comentario