Pure ASP.NET and AJAX

Hi

I want to learn ajax but all the tutorials I find are about php and ajax.  I am not really interested in ready made ajax controls, i want to manually learn how to implement ajax with asp.net.

Does anyone know of any tutorials for asp.net and ajax?

thanks
LVL 1
narmi2Asked:
Who is Participating?
 
TornadoVCommented:
Sorry, I didn't know you're using 2003, here is another link, it's in C# though, but you can use this tool (http://www.developerfusion.co.uk/utilities/convertvbtocsharp.aspx) to translate C# to VB.NET:

http://www.15seconds.com/issue/050526.htm
0
 
TornadoVCommented:
0
 
deightonprogCommented:
are you wanting to use c# or VB?

I found this useful

http://aspalliance.com/716
0
Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

 
narmi2Author Commented:
I'm not interested in atlas as we are still using vs.net 2003.

Thanks deighton, thats the sort of thing i am after, but vb.net would be nice! :)
0
 
narmi2Author Commented:
Thanks
0
 
deightonprogCommented:
As it happens, I'm a vb man too, and I converted something like that example from c to vb

Public Class AjaxClient
    Inherits System.Web.UI.Page

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub
    Protected WithEvents countryList As System.Web.UI.WebControls.DropDownList
    Protected WithEvents stateList As System.Web.UI.WebControls.DropDownList

    'NOTE: The following placeholder declaration is required by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


        Dim countryStateXml As CountryStateXML = New CountryStateXML

        '//Getting the list of countries in an ArrayList
        Dim countries As ArrayList = countryStateXml.GetCountryList()

        '//Populating country combo box
        Dim index As Integer
        For index = 0 To countries.Count - 1

            countryList.Items.Add(countries(index).ToString())


            '                  //Getting the list of states for a given in an ArrayList

        Next

        Dim states As ArrayList = countryStateXml.GetStateList(countries(0).ToString())
        '                  //Populating states combo box
        For index = 0 To states.Count - 1

            stateList.Items.Add(states(index).ToString())

        Next

    End Sub

End Class

Imports System
Imports System.Collections
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Web
Imports System.Web.SessionState
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls


Public Class AjaxServer
    Inherits System.Web.UI.Page

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub

    'NOTE: The following placeholder declaration is required by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        If Not IsPostBack Then

            Dim selectedCountry As String = Request("SelectedCountry")
            If (selectedCountry.Length > 0) Then

                Response.Clear()
                Dim countryStateXml As CountryStateXML = New CountryStateXML

                '//For a given country, getting country and states under that country in XML format.
                Dim statesString As String = countryStateXml.GetStatesXMLString(selectedCountry)
                Response.Clear()
                Response.ContentType = "text/xml"

                Response.Write(statesString)
                '//end the response
                Response.End()

            Else

                '                        //clears the response written into the buffer and end the response.
                Response.Clear()
                Response.End()






                '      //clears the response written into the buffer and end the response.
                Response.Clear()
                Response.End()


            End If
        End If

    End Sub

End Class





Imports System
Imports System.Web
Imports System.Text
Imports System.IO
Imports System.Collections
Imports System.Xml
Imports System.Xml.XPath
Imports System.Xml.xsl






Public Class CountryStateXML

    'This class acts as a data source for countries and states data. Following are the list of uses.
    '      Retuning list of countries present in CountriesAndStates.xml file as ArrayList
    '      Retuning list of states for a given country as ArrayList or XML Document in a string
    Private xPathDoc As XPathDocument

    Public Sub New()
        Try
            '//Loads the CountriesAndStates.xml file into XPathDocument
            xPathDoc = New XPathDocument(HttpContext.Current.Server.MapPath("~/xmlxsl/CountriesAndStates.xml"))

        Catch er As Exception
            Throw er
        End Try

    End Sub

    '            /// <summary>
    '            /// This function retuns list of states for a given country as XML Document in a string
    '            /// and this value is used in client side java script to populate state combo box.
    '            /// Functionality: Transform the CountriesAndStates xml string into another XML string having the single country
    '            /// and states under that country.
    '            /// </summary>

    Public Function GetStatesXMLString(ByVal countryName As String) As String

        '      //Creates a XslTransform object and load the CountriesAndStates.xsl file
        Dim transformToCountryNode As XslTransform = New XslTransform

        Dim xpn As XPathNavigator
        xpn = New XPathDocument(HttpContext.Current.Server.MapPath("~/xmlxsl/CountriesAndStates.xsl")).CreateNavigator()

        transformToCountryNode.Load(xpn, New XmlUrlResolver)


        '//TransformToCountryNode.Load(new XPathDocument(HttpContext.Current.Server.MapPath("~/xmlxsl/CountriesAndStates.xsl")).CreateNavigator(), new XmlUrlResolver(), this.GetType().Assembly.Evidence);

        '            //Creating the XSLT parameter country-name and setting the value
        Dim xslArgs As XsltArgumentList = New XsltArgumentList
        xslArgs.AddParam("country-name", "", countryName)


        '      // Memory stream to store the result of XSL transform
        Dim countryNodeMemoryStream As MemoryStream = New MemoryStream
        Dim countryNodeXmlTextWriter As XmlTextWriter = New XmlTextWriter(countryNodeMemoryStream, Encoding.UTF8)
        countryNodeXmlTextWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'")

        '                  //transforming the current XML string to get the state XML string
        transformToCountryNode.Transform(xPathDoc, xslArgs, countryNodeXmlTextWriter)
        '                  //TransformToCountryNode.Transform(XPathDoc, XslArgs,  CountryNodeXmlTextWriter, null);

        '                  //reading the XML string using StreamReader and return the same
        countryNodeXmlTextWriter.Flush()
        countryNodeMemoryStream.Position = 0
        Dim countryNodeStreamReader As StreamReader = New StreamReader(countryNodeMemoryStream)
        Return countryNodeStreamReader.ReadToEnd()

    End Function

    '/// <summary>
    '/// This function retuns list of states for a given country ( present in CountriesAndStates.xml file) in an ArrayList
    '/// </summary>
    Public Function GetStateList(ByVal CountryName As String) As ArrayList

        '//creating a XPathNodeIterator object for the state nodes under a perticular country with the help of XPath
        Dim xPathNav As XPathNavigator = xPathDoc.CreateNavigator()
        Dim xPathNodeIter As XPathNodeIterator = xPathNav.Select("/countries/country[@name='" + CountryName + "']")

        Dim stateArrayList As ArrayList = New ArrayList

        '//iterating through the state nodes and creating the state Arraylist
        If (xPathNodeIter.Current.HasChildren And xPathNodeIter.MoveNext()) Then

            xPathNodeIter = xPathNodeIter.Current.SelectChildren("state", "")
            Do While (xPathNodeIter.MoveNext())

                stateArrayList.Add(xPathNodeIter.Current.Value)
            Loop
        End If
        Return stateArrayList
    End Function
    '
    '            /// <summary>
    '            /// This function retuns list of countries ( present in CountriesAndStates.xml file) in an ArrayList
    '            /// </summary>
    Public Function GetCountryList() As ArrayList

        '//creating a XPathNodeIterator object for all the country nodes with the help of XPath
        Dim xPathNav As XPathNavigator = xPathDoc.CreateNavigator()
        Dim xPathNodeIter As XPathNodeIterator = xPathNav.Select("/countries/country")

        Dim countryArrayList As ArrayList = New ArrayList

        '//iterating through the county nodes and creating the country arraylist
        Do While (xPathNodeIter.MoveNext())
            countryArrayList.Add(xPathNodeIter.Current.GetAttribute("name", ""))
        Loop
        Return countryArrayList
        Exit Function


    End Function





End Class








//Global XMLHTTP Request object
var XmlHttp;

//Creating and setting the instance of appropriate XMLHTTP Request object to a “XmlHttp” variable  
function CreateXmlHttp()
{
      //Creating object of XMLHTTP in IE
      try
      {
            XmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
      }
      catch(e)
      {
            try
            {
                  XmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(oc)
            {
                  XmlHttp = null;
            }
      }
      //Creating object of XMLHTTP in Mozilla and Safari
      if(!XmlHttp && typeof XMLHttpRequest != "undefined")
      {
            XmlHttp = new XMLHttpRequest();
      }
}

//Gets called when country combo box selection changes
function CountryListOnChange()
{
      var countryList = document.getElementById("countryList");

      //Getting the selected country from country combo box.
      var selectedCountry = countryList.options[countryList.selectedIndex].value;
      
      // URL to get states for a given country
      var requestUrl = AjaxServerPageName + "?SelectedCountry=" + encodeURIComponent(selectedCountry);
      CreateXmlHttp();
      
      // If browser supports XMLHTTPRequest object
      if(XmlHttp)
      {
            //Setting the event handler for the response
            XmlHttp.onreadystatechange = HandleResponse;
            
            //Initializes the request object with GET (METHOD of posting),
            //Request URL and sets the request as asynchronous.
            XmlHttp.open("GET", requestUrl,  true);
            
            //Sends the request to server
            XmlHttp.send(null);            
      }
}


//Called when response comes back from server
function HandleResponse()
{
      // To make sure receiving response data from server is completed
      if(XmlHttp.readyState == 4)
      {
            // To make sure valid response is received from the server, 200 means response received is OK
            if(XmlHttp.status == 200)
            {                  
                  ClearAndSetStateListItems(XmlHttp.responseXML.documentElement);
            }
            else
            {
                  alert("There was a problem retrieving data from the server." );
            }
      }
}

//Clears the contents of state combo box and adds the states of currently selected country
function ClearAndSetStateListItems(countryNode)
{
    var stateList = document.getElementById("stateList");
      //Clears the state combo box contents.
      for (var count = stateList.options.length-1; count >-1; count--)
      {
            stateList.options[count] = null;
      }

      var stateNodes = countryNode.getElementsByTagName('state');
      var textValue;
      var optionItem;
      //Add new states list to the state combo box.
      for (var count = 0; count < stateNodes.length; count++)
      {
               textValue = GetInnerText(stateNodes[count]);
            optionItem = new Option( textValue, textValue,  false, false);
            stateList.options[stateList.length] = optionItem;
      }
}

//Returns the node text value
function GetInnerText (node)
{
       return (node.textContent || node.innerText || node.text) ;
}





var AjaxServerPageName;
AjaxServerPageName = "AjaxServer.aspx";



0
 
deightonprogCommented:
The things you need to know about are

1) triggering events on the client using java script

2) creating the XMLHTTP object and a handler function in java script

3) creating a form which creates and writes xml to its response stream.

4) picking up the xml in the javascript function and populating fields/carrying out tasks accordingly.

The xml part of the tutorial seemed a little over complex to me, I tend to use simpler xml in my work

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.