?
Solved

Pure ASP.NET and AJAX

Posted on 2006-05-18
7
Medium Priority
?
1,006 Views
Last Modified: 2008-03-17
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
0
Comment
Question by:narmi2
  • 3
  • 2
  • 2
7 Comments
 
LVL 11

Expert Comment

by:TornadoV
ID: 16710121
0
 
LVL 18

Assisted Solution

by:deighton
deighton earned 800 total points
ID: 16710361
are you wanting to use c# or VB?

I found this useful

http://aspalliance.com/716
0
 
LVL 1

Author Comment

by:narmi2
ID: 16710400
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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 11

Accepted Solution

by:
TornadoV earned 1200 total points
ID: 16710509
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
 
LVL 1

Author Comment

by:narmi2
ID: 16710530
Thanks
0
 
LVL 18

Expert Comment

by:deighton
ID: 16710609
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
 
LVL 18

Expert Comment

by:deighton
ID: 16710654
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

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
This Micro Tutorial will teach you how to add a cinematic look to any film or video out there. There are very few simple steps that you will follow to do so. This will be demonstrated using Adobe Premiere Pro CS6.
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…
Suggested Courses
Course of the Month14 days, 7 hours left to enroll

839 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question