Click here to Skip to main content
15,894,955 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Hi ,

I am facing the problem of the button click which trigger the code behind, post back the page and the data which i bind with XMLHttp Ajax+ JSON + XML.

I'm using VS2010 (VB.Net) Would you help me go through which part get wrong? Thank you for any help offered.

HTML
Product.xml
--------------
<?xml version="1.0" encoding="utf-8" ?>
<table>
  <row>
    <ProductID>1</ProductID>
    <Product>Business Card</Product>
  </row>
  <row>
    <ProductID>2</ProductID>
    <Product>Greeting/Invitation Card</Product>
  </row>
  <row>
    <ProductID>3</ProductID>
    <Product>PostCard</Product>
  </row>
</table>


CardType.xml
-------------
<?xml version="1.0" encoding="utf-8" ?>
<table>
  <row>
    <ProductID>1</ProductID>
    <CardID>A</CardID>
    <CardName>Card A</CardName>    
  </row>
  <row>
    <ProductID>1</ProductID>
    <CardID>B</CardID>
    <CardName>Card B</CardName>
  </row>
  <row>
    <ProductID>1</ProductID>
    <CardID>C</CardID>
    <CardName>Card C</CardName>
  </row>
  <row>
    <ProductID>1</ProductID>
    <CardID>D</CardID>
    <CardName>Card D</CardName>
  </row>
  <row>
    <ProductID>2</ProductID>
    <CardID>A</CardID>
    <CardName>Card A</CardName>
  </row>
  <row>
    <ProductID>2</ProductID>
    <CardID>B</CardID>
    <CardName>Card B</CardName>
  </row>
  <row>
    <ProductID>3</ProductID>
    <CardID>A</CardID>
    <CardName>Card A</CardName>
  </row>
  <row>
    <ProductID>3</ProductID>
    <CardID>B</CardID>
    <CardName>Card B</CardName>
  </row>
  <row>
    <ProductID>3</ProductID>
    <CardID>C</CardID>
    <CardName>Card C</CardName>
  </row>
</table>


HTML
Default2.aspx
---------------------------------------------------------------------
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
     <style type="text/css">
        .ProgressBox
        {
	        width:600px;
	        height:200px;
	        background-color:Transparent;
	        border:gray 0px solid;
	        position: absolute;
	        z-index: 2;
	        color:Blue;
	        font-size:30px;
        }
        .alpha
        {
	        width: 100%;
	        height: 100%;
	        background: url(images/alpha.png) repeat;
	        position: absolute;
	        top: 0;
	        left: 0;
	        z-index: 100;
	        display: none;
        }
    </style>
     <script src="<%=resolveurl("~/Scripts/jquery.js") %>" type="text/javascript"></script>
      <script language="javascript" type="text/javascript" src="<%=resolveurl("~/Scripts/Default2.js") %>"></script>
    <script language="javascript" type="text/javascript">
        var is_ie = (navigator.userAgent.indexOf('MSIE') >= 0) ? 1 : 0;
        var is_ie5 = (navigator.appVersion.indexOf("MSIE 5.5") != -1) ? 1 : 0;
        var xmlHttp;

        var vDDLProductsClientID;
        var vDDLCategoriesClientID;
        var vhndProductId;

        window.onload = function () {

            vDDLProductsClientID = '<%= ddlProduct.ClientID %>';
            vDDLCategoriesClientID = '<%= ddlCardType.ClientID %>';
            vhndCardType = '<%= hndCardType.ClientID %>';

            document.getElementById('alpha').style.display = 'none';

            // Get the height and Width of the screen
            var viewportwidth;
            var viewportheight;

            if (typeof window.innerWidth != 'undefined') {
                viewportwidth = window.innerWidth,
                viewportheight = window.innerHeight
            }
            else if (typeof document.documentElement != 'undefined' &&
                     typeof document.documentElement.clientWidth != 'undefined' &&
                     document.documentElement.clientWidth != 0
                    ) {
                viewportwidth = document.documentElement.clientWidth,
                        viewportheight = document.documentElement.clientHeight
            }
            else {
                viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
                    viewportheight = document.getElementsByTagName('body')[0].clientHeight
            }
            document.getElementById('alpha').style.height = viewportheight;
            document.getElementById('alpha').style.width = viewportwidth;

            document.getElementById('Progress').style.top = ((viewportheight - 200) / 2) + "px";
            document.getElementById('Progress').style.left = ((viewportwidth - 400) / 2) + "px";
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <div id="alpha" class="alpha">
        <div id="Progress" class="ProgressBox">
            <img src="Images/ajaxLoader.gif" alt="" width="200px" height="200px" />Working on your Request
        </div>
    </div>
    <div>
         <table>
            <tr>
                <td>Product</td>
                <td><asp:DropDownList runat="server" ID="ddlProduct" Width="250px"  onchange="BindProducts(this.id)">
                    </asp:DropDownList>
                </td>               
               
            </tr>
            <tr>
                <td>Card Types</td>
                <td><asp:DropDownList runat="server" ID="ddlCardType" Width="250px" >
                    <asp:ListItem Text="Select" Value="0"></asp:ListItem>
                    </asp:DropDownList>
                    <asp:HiddenField ID="hndCardType" runat="server" Value="0" />
                </td>
             
            </tr>
            <tr>
                <td colspan="2" style="text-align:right">
                    <asp:Button ID="btnProcess" Text="Process" runat="server" Width="100px" 
                        onclick="btnProcess_Click" OnClientClick="AssignHiddenValues()" />
                </td>
            </tr>
        </table>
    </div>
    <asp:UpdatePanel ID="updatePanelOrders" runat="server">
            <ContentTemplate>
                <asp:Label ID="lblOutput" runat="server"></asp:Label>
            </ContentTemplate>
     </asp:UpdatePanel>
    </form>
</body>
</html>


Default2.aspx.vb
--------------------------------
Imports System.Data

Partial Class Default2
    Inherits System.Web.UI.Page

    Protected Sub btnProcess_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnProcess.Click

    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            BindCategoriesDropdown()
        End If
    End Sub
    Public Sub BindCategoriesDropdown()
        Dim ds As New DataSet
        Dim dv As New DataView


        ds.ReadXml("D:\Research\CINDY\App_Data\Xml\Product.xml")
        dv = ds.Tables(0).DefaultView
        If dv.Count > 0 Then
            ddlProduct.Items.Clear()

            For i As Integer = 0 To dv.Count - 1

                Dim listitem As New ListItem
                listitem.Text = dv.Item(i).Item("Product")
                listitem.Value = dv.Item(i).Item("ProductID")
                ddlProduct.Items.Add(listitem)
            Next
        End If
    End Sub

End Class


GetAjaxResponse.aspx.vb
------------------------------
 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim strResponse As String = String.Empty        
        
        If (Request.QueryString("CallType") <> "") Then
            Dim strCallType As String = Request.QueryString("CallType").ToString
            
           If strCallType = "getCard" Then
                strResponse = GetCardInfo(Request.QueryString("ProductID").ToString)
            End If
        End If

        Response.Clear()
        Response.ContentType = "text/xml"
        Response.Write(strResponse)
        Response.End()

 End Sub


 Public Function GetCardInfo(ByVal ProductID As Integer) As String
        Dim ds As New DataSet
        Dim dv As New DataView
       
        ds.ReadXml("D:\Research\CINDY\App_Data\Xml\CardType.xml")
        dv = ds.Tables(0).DefaultView
        dv.RowFilter = "ProductID= '" & ProductID & "'"
        Dim CardList As IList(Of Card) = New List(Of Card)
        If dv.Count > 0 Then
            For i As Integer = 0 To dv.Count - 1
                Dim CardInfo As New Card()
                CardInfo.CardName = dv.Item(i).Item("CardName")
                CardInfo.CardID = dv.Item(i).Item("CardID")
              
                CardList.Add(CardInfo)
            Next
        End If
        '//delay the response to see the loading... message on the dropdown 
        System.Threading.Thread.Sleep(500)

        Dim objSerializer As System.Web.Script.Serialization.JavaScriptSerializer = New System.Web.Script.Serialization.JavaScriptSerializer
        Return objSerializer.Serialize(CardList)
    End Function

JavaScript
Default2.js
---------------------
function BindProducts(id) {
    var url = '/Member/Order/getAJAXResponse.aspx?CallType=getCard&ProductID=' + document.getElementById(id).value;
    xmlHttp = createAjaxObject();
    if (xmlHttp) {
        xmlHttp.open('get', url, true);
        xmlHttp.onreadystatechange = HandleBindCardResponse;
        xmlHttp.send(null);
    }
}

function HandleBindCardResponse(result) {
    if (xmlHttp.readyState == 4) {
        // here is the response
        var strResponse = xmlHttp.responseText;

        //parsing the JSON Response
        var ArrCategories = eval("(" + strResponse + ")");

        //Getting Paper DrowDown
        $('#' + vDDLCategoriesClientID).empty();

        var options = $('#' + vDDLCategoriesClientID).attr('options');
        options[options.length] = new Option("Select", "", true, true);

        //Looping the array
        for (var intIndex = 0; intIndex < ArrCategories.length; intIndex++) {
            var options = $('#' + vDDLCategoriesClientID).attr('options');
            options[options.length] = new Option(ArrCategories[intIndex]["CardName"], ArrCategories[intIndex]["CardID"], true, true);

        }
        $('#' + vDDLCategoriesClientID).get(0).selectedIndex = 0;


        xmlHttp.abort();
        
    } else {
        //Getting the paper drop down list
        //var ddlPaper = document.getElementById('<%=ddlModel.ClientID %>');
        $('#' + vDDLCategoriesClientID).empty();

        var options = $('#' + vDDLCategoriesClientID).attr('options');
        options[options.length] = new Option("Loading...", "", true, true);

    }
}

/* function to create Ajax object */
function createAjaxObject() {
    var ro;
    var browser = navigator.appName;

    if (browser == "Microsoft Internet Explorer") {
        if (xmlHttp != null) {
            xmlHttp.abort();
        }
        ro = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else {
        if (xmlHttp != null) {
            xmlHttp.abort();
        }
        ro = new XMLHttpRequest();
    }
    return ro;
}

/* Get the XML Http Object */
function GetXmlHttpObject(handler) {
    var objXmlHttp = null;
    if (is_ie) {
        var strObjName = (is_ie5) ? 'Microsoft.XMLHTTP' : 'Msxml2.XMLHTTP';

        try {
            objXmlHttp = new ActiveXObject(strObjName);
            objXmlHttp. önreadystatechange = handler;
        }
        catch (e) {
            alert('Object could not be created');
            return;
        }
    }
    return objXmlHttp;
}

function AssignHiddenValues() {
    if (parseInt(document.getElementById(vDDLCategoriesClientID).value) > 0) {
        document.getElementById(vhndCardType).value = document.getElementById(vDDLCategoriesClientID).value;
        return true;
    }
    else {
        alert('Please select Product and Card Process');
        return false;
    }
}
Posted
Updated 7-Feb-12 0:29am
v2
Comments
Slacker007 7-Feb-12 6:30am    
Edits made: some formatting and title.
Herman<T>.Instance 7-Feb-12 6:32am    
too many lines to see the error. Did you do a debug? On which line the exception occurs? What is the exception?
cindy_03 7-Feb-12 20:12pm    
It is postback problem cause the dropdownlist which bind with XML-HTTP_JSON lost data.

EnableViewState for Drop down control (default it is false)
 
Share this answer
 
Hi Cindy,

Verify the below url. it may help you to solve this issue.

http://www.dotnettwitter.com/2012/02/implementing-xml-http-ajax-with-json-in.html[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900