ASP.NET and Ajax - using XmlHttpRequest


In this post, I will show how to use the XMLHttpRequest object in asp.net.Here’s an example that fetches the Product details by category.Create a new web application and add following code on Default.aspx page( I have used Ajax.aspx). Ajax.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Ajax.aspx.cs" Inherits="Ajax" %>

<!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></title>

  <script type="text/javascript">
      function GetXmlHttpObject(handler) {
          var objXmlHttp = null
          if (navigator.userAgent.indexOf("Opera") >= 0) {
              alert("This example doesn't work in Opera")
              return
          }
          if (navigator.userAgent.indexOf("MSIE") >= 0) {
              var strName = "Msxml2.XMLHTTP"
              if (navigator.appVersion.indexOf("MSIE 5.5") >= 0) {
                  strName = "Microsoft.XMLHTTP"
              }
              try {
                  objXmlHttp = new ActiveXObject(strName)
                  objXmlHttp.onreadystatechange = handler
                  return objXmlHttp
              }
              catch (e) {
                  alert("Error. Scripting for ActiveX might be disabled")
                  return
              }
          }
          if (navigator.userAgent.indexOf("Mozilla") >= 0) {
              objXmlHttp = new XMLHttpRequest()
              objXmlHttp.onload = handler
              objXmlHttp.onerror = handler
              return objXmlHttp
          }
      }

      function GetProduct(id) {
          var url = "Details.aspx?CatId=" + id;
          xmlHttp = GetXmlHttpObject(stateChanged);
          xmlHttp.open("GET", url, true);
          xmlHttp.send(null);
      }


      function stateChanged() {
          if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
              document.getElementById('ProductDetails').innerHTML = xmlHttp.responseText;
          }
      }

  </script>

</head>
<body>
  <form id="form1" runat="server">
  <div>
      <div>
          <asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource1"
              DataTextField="CategoryName" DataValueField="CategoryID">
          </asp:DropDownList>
      </div>
      <div id="ProductDetails">
      </div>
  </div>
  <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:northwindConnectionString %>"
      SelectCommand="SELECT [CategoryID], [CategoryName] FROM [Categories]"></asp:SqlDataSource>
  </form>
</body>
</html>

Ajax.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Ajax : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
      if (!Page.IsPostBack)
      {
          DropDownList1.DataBind();
          DropDownList1.Items.Insert(0, "");
      }
      DropDownList1.Attributes["onChange"] = "GetProduct(this.value);";
      HttpResponse myHttpResponse = Response;
      HtmlTextWriter myHtmlTextWriter = new HtmlTextWriter(myHttpResponse.Output);
      DropDownList1.Attributes.AddAttributes(myHtmlTextWriter);


  }
}

And finally create Details.aspx page and remove everything from .aspx page except the first line. write down following code on Page_Load event of details.aspx page.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Data.SqlClient;

public partial class Details : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
       Response.Clear();
       StringBuilder sb = new StringBuilder();
       sb.Append("<br />");
       string connstr = System.Configuration.ConfigurationManager.ConnectionStrings["northwindConnectionString"].ConnectionString;
       string query = "SELECT * FROM Products WHERE CategoryId = @CustId";
       SqlConnection conn = new SqlConnection(connstr);
       SqlCommand cmd = new SqlCommand(query, conn);
       cmd.Parameters.AddWithValue("@CustId", Request.QueryString["CatId"]);
       conn.Open();
       SqlDataReader dr = cmd.ExecuteReader();
       while (dr.Read())
       {
           sb.Append(dr[1].ToString() + "<br />");
           sb.Append(dr[2].ToString() + "<br />");
           sb.Append(dr[3].ToString() + "<br />");
           sb.Append(dr[4].ToString() + "<br />");
           sb.Append(dr[5].ToString() + "<br />");
           sb.Append(dr[6].ToString() + "<br />");
       }
       dr.Close();
       dr.Dispose();
       conn.Close();
       conn.Dispose();
       Response.Write(sb.ToString());
       Response.End();

   }
}

Post a Comment

Please do not post any spam link in the comment box😊

Previous Post Next Post

Blog ads

CodeGuru