Call .net service from javascript
While development, you will find it quite frequent that you need to call web service using JavaScript. Calling a web service from JavaScript was not an easy task earlier. First, you need to create a proxy class for JavaScript and then write bunch of java script code to call that webService but Microsoft ASP.NET Ajax has made our task easier. You can now call web services from JavaScript very easily with just few line of JavaScript. It also allows you to handle errors scenario and performs even better than the .net service call.
Let’s understand it with an example.
Create a simple Krishna web service which will just print ‘Krishna is great’ and then we will call this web service using JavaScript. Following is a code for web service.
Create a webservice in your project and ada the following line at the top of the web service
[System.Web.Script.Services.ScriptService]
[WebService(Namespace = "https://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
As commented by the Microsoft themselves, this addition 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 returns some message.
[WebMethod]
public string PrintMessage(string name)
{
//int.Parse(name);
return "Krishna is great. "+name+" is his devotee";
}
Now, add web service reference to the aspx page where you will call this web service and display the data. Inside form tag of aspx page, add following lines.
<form id="form1" runat="server">
<asp:ScriptManager id="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/WebService1.asmx" />
</Services>
</asp:ScriptManager>
</form>
If you prefer to add the service reference from code behind file, then you can do it as shown below:
ScriptManager1.Services.Add(new ServiceReference("~/WebService1.asmx "));
Add a text box to input your name and a button to trigger Web Service request:
<asp:TextBox ID="txtName" runat="server" />
<input type="button" value="Send" id="SendButton" onclick="return SendRequest()" />
Now add JavaScript functions to call web service and process web service result. We will be adding the following JavaScript functions
SendRequest - this function will send asynchronous request to the Web Service
OnComplete - this function will receive result from the Web Service
OnError - this function will be triggered if an error occurs while executing Web Service
OnTimeOut - this function will be triggered if Web Service will not respond
function SendRequest() {
var name = $("#txtName").val();
auth.WebService1.PrintMessage(name, OnComplete, OnError, OnTimeOut);
}
We pass the text input to the webservice and invoke printmessage function
Web service method is called using full reference i.e namespace.class.functionName
function OnComplete(arg) {
$("#txtName").val(arg);
}
If the request is successful, returned result is displayed in the textbox
function OnTimeOut(arg) {
alert("timeOut has occured");
}
If connection fails, then we get timeout alert box
function OnError(arg) {
alert("error has occured: " + arg._message);
}
If some error occurs, then we get error alert box.
We can also show the details of the error like stack trace, status, exception type etc. use the following code to view error details
alert ("Stack Trace: " + arg._stackTrace + "\r\n" +
"Error: " + arg._message + "\r\n" +
"Status Code: " + arg._statusCode + "\r\n" +
"Exception Type: " + arg._exceptionType + "\r\n" +
"Timed Out: " + arg._timedOut);
That’s it. Now let’s run the project and see this in action.
On running the project, we get the following screen
Enter your name as input
Click on send button
As we see above, result returned from service is displayed in textbox
To create the error scenario, I parse the input string to integer which will generate format exception.
[WebMethod]
public string PrintMessage(string name)
{
int.Parse(name);
return "Krishna is great. "+name+" is his devotee";
}
On clicking send, we get the error as shown below.
Detailed error will be shown as:
With this, we have a functioning client-side JavaScript code that calls server-side Web Service and handles returned response:
Conclusion
The described client-to-server communication model where client-side JavaScript code invoking Web Service methods provides us a lot of flexibility to extend the web site functionality. At the same time the traffic is minimal where we send only the input data required by the Web Method and we receive only the return value from the method being invoked
here
Note: Images used on this website
are either a production of Bhaktivedanta Book Trust(https://www.krishna.com), Iskcon
Foundation or were found in google search under "Free to use and share". If any
of the images presented here violates copyright issues or infringes anyone copyright
or are not under "Fair use", then please bring it to our notice. Read
Disclaimer for more.
Share this to your friends. One of your friend is
waiting for your share.
Related Articles
Calling web service asynchronously using jquery ajax
Database cannot be opened due to inaccessible files or insufficient memory or disk space
Working with AJAX cascading dropdown
Simple Ajax client server Example
Call .net service from javascript
Testing performance issues with reflection
Tips and Tricks with ajax accordion control
Tips and tricks with ajax calendar
Trigger custom or manual postback in ASP.NET
Post Comment