Call Asp .Net WebService Using Javascript

在這裡MARK一下一個覺得不錯的JS調用WEBSERVICE實例介紹

 

We all know that the goal of modern web application is to make application as robust as possible. In order to do that user should feel that everything is happening on the client side and that can be achieved by “AJAX”. Formally known as AJAX is short form of Asynchronous JavaScript and XML. So what it does. Well it brings data from server and posts it back to the users without causing a post back and that sounds like a more responsive and robust application to the  user. It improves user interaction of your application.

One way is to put your controls in update panel and update them with other control’s asynchronous post back. Sometime it is good sometimes it is not a very good idea. I will give you an example. I had a task where I had to develop a collapsible panel after reading from data from database. The count of this collapsible panel was dependent on data rows coming back from database according to user selection. At first I thought of using ASP .NET collapsible panel extender control and found out how to do it. But soon I realized that this is going to give me a performance issue as the number of rows start increasing. Even if I put that in a “Datalist” control and if I get 50 data rows virtually I will be creating 100 panels on the page.  So I dropped that idea and came up with something else.

It involved some JavaScript and a web service but the performance was issue was gone. In this case the first challenge was to call a web service from JavaScript and catch the web method results through JavaScript. In this article I will show you simple method how you can call a web service method from using JS and display it back to the users using JS.

 I assume you guys have a basic knowledge of web service and javascript as well. If you don’t have any idea about web service I suggest you go through this article which explains how to create a web service and add web methods in that.  Again if you don’t know anything about javascript you can go through this article which will brief you about basic syntax and methods.

 

SETP - 1 (Creating a web service)

Creating a web service was never easier than this when you are having Visual studio. First let’s open Visual Studio and go to menu then click on create and then select a new web service. Name your web service whatever you want. Once your web service gets created it comes with inbuilt Hello world web method if you want to keep you can else remove it and create your own web method which access databases and returns some result.

But before we go ahead and do that let me add one line at the top of my web service which is:

 

[System.Web.Script.Services.ScriptService]

This enables your web service to be accessible by JavaScript. Now that our web service is accessible by JavaScript let’s create a web method which queries database and returns some result.

 

        [WebMethod]

public static string[] GetHints(string type)

{

List<string> Results = new List<string>();

DbConnection _Conn = GetDBConnection();

DbCommand _Cmd = _Conn.CreateCommand();

_Cmd.CommandText = "sp_GetHints";

_Cmd.CommandType = CommandType.StoredProcedure;

_Cmd.Parameters.Add(new SqlParameter("@Param", SqlDbType.VarChar, 50));

_Cmd.Parameters["@Param"].Value = type;

_Conn.Open();

DbDataReader _Reader = _Cmd.ExecuteReader();

while (_Reader.Read())

{

Results.Add(_Reader["ID"].ToString() + " - " + _Reader["Name"].ToString());

}

_Reader.Close();

_Conn.Close();

_Hints = Results.ToArray();

return _Hints;

}

 

This method takes one argument which is type and fetches results back. To give you little bit idea about the returning result let me describe it as below. When I pass “USER” as a parameter to the web service it will return me something like this.

SAD – Super Admin

ADM-Admin

MDR – Moderator

CTM – Content moderator

Etc.

This result was to be displayed to the user when he/she is a super admin and is adding new users to his system and assigning roles to them. These values are displayed in a drop down and when this drop down is get focused we have to display above hints to the right hand side of the drop down for user preferences.  Think of a user, how surprised he/she would be to see this hints being displayed without even clicking a single button or without deviating from what he is doing. Ok so now you have the idea what is the result of the web method is and how result has to be displayed to the page let’s start with the hard part now.

STEP – 2 (Creating JavaScript functions to call web service)

Before we go ahead and create JavaScript functions first let’s add web service reference to the aspx page where you are planning to call this web service and display the data. In your aspx page inside form tag add following lines.

<asp:ScriptManager id="ScriptManager1" runat="server">   

<Services>

<asp:ServiceReference Path="~/ParameterService.asmx" />

Services>

asp:ScriptManager>

Add Script manager reference and add a service reference by adding a path to it. In my case I named my service as ParameterService.asmx. Now let’s write our first JavaScript function which actually calls the web service

 

function GetHintsByType(param)

{

var test = param;

WebserviceNamespace.NameOfWebService.GetHints(test, OnWSRequestComplete,OnWSRequestFailed);

}

 

Well it’s as simple as it seems we are just calling a method and passing parameter from the page’s control to this function and calling a web method by referencing its Namespace.Webservicename.Webmethod.

You must have noticed two more things which are   “OnWSRequestComplete”, “OnWSRequestFailed”. These are the names of the method once the web service is called and we have received some response from our web service either result or error. If there is any error the second method is called if the call was successful first method will be called.

Let’s examine what these methods contains inside them.

 

function OnWSRequestComplete(results)

{

if (results != null)

{

CreateHintDivs(results);

}

}

This function simply checks if the result is null or not. If it’s not null it will call another method passing this result object to it. We will take a look at this function in while but let’s finish the small function that we have called OnWSRequestFailed. This function looks as below.

 

 

function OnWSRequestFailed(error)

{

alert("Error getting hints");

}

 

Again this function can be as complex as below which will show you entire error message.

 

function OnWSRequestFailed(error)

{

alert("Stack Trace: " + error.get_stackTrace() + "\r\n" +

"Error: " + error.get_message() + "\r\n" +

"Status Code: " + error.get_statusCode() + "\r\n" +

"Exception Type: " + error.get_exceptionType() + "\r\n" +

"Timed Out: " + error.get_timedOut());

}

Finally let’s take a look at the function which is going to add this result on the page.

 

 

function CreateHintsDivs(result)

{

for(var k=0;k

{

var html ="";

html = html + "
"+result[k].Hints +"

"

}

var hintdiv = document.getElementById("HindDivID");

hintdiv.innerHTML = html;

}

 

"HindDivID" is the ID of the div which is already on the page and which is going to hold these hints for us. Finally I am appending the html that I created dynamically to this div by its innerHtml property.

Finally on my page load event I will bind my main function to the dropdown as below.

drpRole.Attributes.Add("onFocus", "GetHintsByType('"+"Roles"+"')");

That’s it. This should all what we wanted and we should be able to display results back to the uses without causing any post backs.

 

 

來源:http://www.a2zdotnet.com/View.aspx?Id=15

posted @ 2010-10-26 16:15  lavandachen  阅读(366)  评论(0编辑  收藏  举报