Custom Javascript Ajax for ASP.NET

I wrote some basic Javascript functions and would like to know how to enable asynchronous callbacks in a C # 4.0 / ASP.net project using this JS code.

For example, I have a script that increments a number when clicked. When pressed again, the number decreases. I basically load the number from the database, then hide one <span> and show the other with the corresponding reduced number on click. This is not complicated javascript; his simple example. Now, when I click the button, I want to send this increase / decrease request to the server in order to update the database number.

I understand that I can accomplish something similar to this example using the AJAX Control Toolkit toggle button. However, I want to know how to use my OWN javascript to create AJAX functionality.

How to do this with C # and my custom Javascript code?

I am not against using the ASP.NET AJAX library, I just do not want to use a ready-made inline control. I want to learn the process of creating my own AJAX functionality. I would suggest that I have to use asp:UpdatePanel , but I don't know how to call C # functions from the client side.

My javascript is not jQuery, in fact I don't want to have anything to do with jQuery until I learn more about javascript and this process.

+7
javascript c #
source share
8 answers

Simple without UpdatePanel:

First add a generic handler (.ashx) to the project. This will be our Http endpoint. Our javascript will call it. We could (and probably should) use a web service endpoint, but this requires processing the response and complicating this example. The handler returns plain text.

 <%@ WebHandler Language="C#" Class="Handler" %> using System; using System.Web; public class Handler : IHttpHandler { // We'll use a static var as our "database". // Feel free to add real database calls to the increment // and decrement actions below. static int TheNumber = 0; public void ProcessRequest(HttpContext context) { string action = context.Request.QueryString["action"]; if (!string.IsNullOrEmpty(action)) { if (action == "increment") TheNumber++; //database update and fetch goes here else if (action == "decrement") TheNumber--; //database update and fetch goes here } context.Response.ContentType = "text/plain"; context.Response.Write(TheNumber); } public bool IsReusable { get { return false; } } } 

Then create your webpage and add asynchronous javascript.

 <%@ Page Language="C#"%> <html> <head runat="server"> <script type="text/javascript"> // An XMLHttpRequest object is required to make HTTP requests. // Try a couple instantiation strategies to handle different // browser implementations. function createXMLHttpRequest() { try { return new XMLHttpRequest(); } catch (e) { } try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { } try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { } alert("XMLHttpRequest not supported"); return null; } function callHandler(action) { var xmlHttpReq = createXMLHttpRequest(); // We're interested in an asychronous request so we define a // callback function to be called when the request is complete. xmlHttpReq.onreadystatechange = function () { if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200) document.getElementById("<%= lbl.ClientID%>").innerHTML = xmlHttpReq.responseText; } xmlHttpReq.open("GET", "Handler.ashx?action=" + action, true); xmlHttpReq.send(null); } </script> </head> <body> <form id="Form1" runat="server"> <div> The Number:&nbsp;<Label runat="server" id="lbl">0</Label> </div> <div> <asp:Button ID="Button1" runat="server" Text="Increment" OnClientClick="callHandler('increment');return false;" /> &nbsp; <asp:Button ID="Button2" runat="server" Text="Decrement" OnClientClick="callHandler('decrement');return false;" /> </div> </form> </body> </html> 

End stream:

  • The webpage user clicks the Increment or Decrement button, which calls our javascript
  • Our javascript sends the request with the desired action to querystring in Handler.ashx
  • Handler.ashx reads the request, increases or decreases its static variable and returns a value
  • Our callback gets the value and updates our interface.
+2
source share

if you use UpdatePanel , it is very simple with calling JavaScript on __doPostBack . See here for example .

0
source share

Take a look at this tutorial around AJAX http://www.w3schools.com/Ajax/Default.Asp

It will give you an overview of using Javascript for GET and POST data using AJAX.

Hope this helps.

0
source share

Here is a link to how you can enable ASP.NET C # with your custom Javascript code.

http://msdn.microsoft.com/en-us/library/bb386450.aspx

It also contains an example VS 2010 project: http://go.microsoft.com/fwlink/?LinkId=185646

Here, in general, what happens here:

In the AjaxIScriptControl solution:

SampleTextBox.cs - takes care of the rendering of the script control on the page; and embedding in client javascript code (js file)

SampleTextBox.js - takes care of functions on the client side and generates a Javascript control object through a prototype

Notes:

  • This example uses the existing ASP.NET Inline Control (you noteTextTextBox inherits the text box and IScriptControl), but you can render any type of HTML control if you inherit the ScriptControl class instead.

  • This solution also chose the separation of the control script code and the website code in two projects, but you can easily make it one.

  • You can easily use another Javascript library in your JS file

In my experience, this is still one of the most elegant ways to include server-side code on the client side if you want to create reusable controls for your site. You use server power to perform initial rendering, providing client-side capabilities through Javascript.

0
source share

If you create your C # functions as WCF REST services or older Script Services , you can easily call your service methods from your JavaScript using the base XmlHttpRequest (without the need for jQuery or UpdatePanels).

Here is the quick jsFiddle I put together: http://jsfiddle.net/ndVeS/

This sample has two text fields; you enter the value in the first, press the button, and then this value is passed to the service (echo service) and returned in the callback. JavaScript code takes this value and populates it with a second text field.

You can define a C # WCF RESTful service, for example:

 [ServiceContract] public class EchoService : IEchoService { [WebGet(UriTemplate="EchoMe?val={theValue}, ResponseFormat=WebMessageFormat.Json)] public string EchoMe(string theValue) { return theValue; } } 

If you handle your calls in this way, you can separate your service logic from your presentation (.aspx files), and this makes testing easier, and you can also separate responsibilities from those who create the user interface from those who create the business functionality.

I have to admit that I'm more of a jQuery person when it comes to this, but I thought it was a great exercise to figure out how XmlHttpRequest works under the hood. It makes you appreciate what jQuery (or similar infrastructure) provides.

Here is a good overview of the XmlHttpRequest object and how to use it: http://www.jibbering.com/2002/4/httprequest.html

Hope this helps.

0
source share
 function GetXmlHttpObject(handler) { var objXMLHttp = null if (window.XMLHttpRequest) { objXMLHttp = new XMLHttpRequest() } else if (window.ActiveXObject) { objXMLHttp = new ActiveXObject("Microsoft.XMLHTTP") } return objXMLHttp; 

}

function GetDropDown () {

 function stateChanged(StatesUpdated) { if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") { document.getElementById('updateplace').innerHTML = xmlHttp.responseText; //"updateplace" is you div id which will hold the new data or new page if (navigator.appName != "Microsoft Internet Explorer") { } } else { //alert(xmlHttp.status); } } xmlHttp = GetXmlHttpObject() if (xmlHttp == null) { alert("Browser does not support HTTP Request"); return; } url = "xyz.aspx" //this might be sent to any post data url = url + "&sid=" + Math.random(); xmlHttp.onreadystatechange = stateChanged; xmlHttp.open("GET", url, true); xmlHttp.send(null); 

}

with the code above, you can send data to any .cs file, where you can change the data and upload it to a new page, which will be loaded into the div for updating, and the method should redirect to a new aspx file.

Hope you have some logic :)

if you have any doubts, contact me @ sankalpa.sam @ gmail.com

0
source share

I know that this is not MVC, what you do, but look at the MVC section on ASP.NET and you will find many examples of AJAX calls there - MVC does not use these awful script -soup creates .NET objects. Most are likely to use jQuery, an open source JavaScript library that can connect to any web application and provides some really nice features.

0
source share

Perhaps you are looking for this:

function ajaxscript () {$ .ajax ({type: "POST", url: | url / methodName |, data: | variable_name |, contentType: "application / json; charset = utf-8", dataType: "json", success: | some javascript here |, error: | some javascript here |});

-one
source share

All Articles