We thought to expand the idea of Ajax request little bit further in order to present a very useful concept for achieving a flexible development approach with in your application. So, CMSN Software presents this tutorial "How to call CSharp function in Ajax " which explains how to call CSharp method using JavaScript via Ajax request.
We think that you have obtained a clear idea about how to load text file content using JavaScript via Ajax request by reading our previous tutorial "Simple Ajax Request".
- JavaScript
- ASP.NET Ajax
- jQuery
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="JavaScriptSample._Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>How to call CSharp function in Ajax | JavaScript Sample</title> <script type="text/javascript"> function getServerTime() { /// <summary> /// Call ServerTime web method via ajax request /// </summary> if (window.XMLHttpRequest) { // for IE7+, Firefox, Chrome, Opera, Safari this.xmlhttp = new XMLHttpRequest(); } else { // for IE6, IE5 try { this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e1) { try { // older version of Msxml this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e2) { this.xmlhttp = null; } } } xmlhttp.onreadystatechange = function() { /// <summary> /// Display server time when success /// </summary> if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { // success Status document.getElementById("ServerTimeResponse").innerHTML = xmlhttp.responseText; } } this.xmlhttp.open("POST", "AjaxServer.asmx/ServerTime", true); this.xmlhttp.send(); } </script> </head> <body> <form id="ServerTimeForm" runat="server"> <div> <input id="ServerTimeButton" type="button" onclick="getServerTime();" value="Get Server Time" /> <div id="ServerTimeResponse" runat="server"> </div> </div> </form> </body> </html>
In our previous tutorial "Simple Ajax Request" JavaScript section We explained the basic steps of creating a Ajax request using JavaScript. So we are not going to repeat same steps here. The main difference here is we are using post method instead of using get method in open(method, url, async) method of the XMLHttpRequest object. And we replace the text file's url by url of the web service.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="MicrosoftAjaxSample._Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>How to call CSharp function in Ajax | Microsoft Ajax Sample</title> <script type="text/javascript"> function getServerTime() { /// <summary> /// Call ServerTime web method via ajax request /// </summary> MicrosoftAjaxSample.AjaxServer.ServerTime(OnComplete, OnError); } function OnComplete(result) { /// <summary> /// Display server time when success /// </summary> document.getElementById("ServerTimeResponse").innerHTML = result; } function OnError(result) { /// <summary> /// show error message when there is an error /// </summary> alert("Error: " + result.get_message()); } </script> </head> <body> <form id="ServerTimeForm" runat="server"> <asp:ScriptManager ID="ServerTimeScriptManager" runat="server"> <Services> <asp:ServiceReference Path="~/AjaxServer.asmx" /> </Services> </asp:ScriptManager> <div> <input onclick="getServerTime();" id="ServerTimeButton" type="button" value="Get Server Time" /> <div id="ServerTimeResponse" runat="server"> </div> </div> </form> </body> </html>
In our previous tutorial "Simple Ajax Request" Asp.Net section we explained that how to access server method using Script Manager. Because of that in this tutorial we are trying to explain how to call CSharp method using Asp.Net Web Service.
The major part of this sample is adding Service Reference to Asp.Net Script Manager. Then Asp.Net Script Manager will take care of rest of the coding. we can do what ever we want in OnComplete function.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="JQuerySample._Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>How to call CSharp function in Ajax | jQuery Sample</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { /// <summary> /// A function to execute after the DOM is ready. /// </summary> $("#ServerTimeButton").click(function() { /// <summary> /// A function to execute when the ServerTimeButton is clicked. /// </summary> $.ajax({ /// <summary> /// Perform an asynchronous HTTP (Ajax) request /// </summary> type: "POST", url: "AjaxServer.asmx/ServerTime", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(response) { /// <summary> /// Display server time when success /// </summary> $('#ServerTimeResponse').html(response.d); }, failure: function(msg) { /// <summary> /// show error message when there is an error /// </summary> $('#ServerTimeResponse').html(msg.d); } }); return false; }); }); </script> </head> <body> <form id="ServerTimeForm" runat="server"> <div> <asp:Button ID="ServerTimeButton" runat="server" Text="Get Server Time" /> <div id="ServerTimeResponse" runat="server"> </div> </div> </form> </body> </html>
This sample also almost same as our previous tutorial "Simple Ajax Request" jQuery section. The major difference here is we are using Ajax request type as "POST" and url as url to our web service. In the success function we can access the response return from server.
//----------------------------------------------------------------------- // <copyright file="AjaxServer.asmx.cs" company="CMSN Software"> // Copyright © 2010 CMSN Software // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses. // </copyright> //----------------------------------------------------------------------- namespace JQuerySample { using System; using System.Globalization; using System.Web.Services; /// <summary> /// Simple web service to return current server time /// </summary> [WebService(Namespace = "http://cmsnsoftware.blogspot.com/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] [System.Web.Script.Services.ScriptService] public class AjaxServer : System.Web.Services.WebService { /// <summary> /// get Server time as string. /// </summary> /// <returns> /// Server time /// </returns> [WebMethod] public string ServerTime() { return DateTime.Now.ToString(CultureInfo.CurrentCulture); } } }
This is very simple web service which contains a web method to return server time.
2 comments:
Post a Comment