Introduction:
In this article,i am going to explain about how to create a ajax based search page using asp.net/c#.
Main:
In articles http://netprogramminghelp.com/ajax/retrieving-data-from-server-using-ajax-post-method/ and
http://netprogramminghelp.com/ajax/ajaxfetching-data-using-get-method/ i explained how to use ajax post
and get methods,In this search page,i am just going to use ajax post method.
In Search.apsx,
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Search.aspx.cs" Inherits="Search" %>
<!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>Untitled Page</title>
<script type="text/javascript">
//global variable for hold XMLHttpRequest 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 {
//it will work if IE have JavaScript version 5.0
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(oc) {
xmlHttp = null;
}
}
//Creating object of XMLHTTP for non-IE browsers
if(!xmlHttp && typeof XMLHttpRequest != "undefined") {
xmlHttp = new XMLHttpRequest();
}
}
//function to search
function NetProgrammingSearch(searchText) {
//create XMLHttpRequest Object
CreateXmlHttp();
//Requested url
var ajaxRequest = "http://localhost/NetProgrammingSearch/Search.aspx?search=" + searchText;
//set callback function
xmlHttp.onreadystatechange = callBackMethod;
//Initializes request
xmlHttp.open("GET", ajaxRequest, true);
//send request
xmlHttp.send(null);
}
function callBackMethod() {
//if request completed sucessfully clear the previous result and show the new search results
if(xmlHttp.readyState == 4) {
if(xmlHttp.status == 200) {
clearResults();
showResults();
}
}
}
//function clear previous results
function clearResults() {
var tableBody = document.getElementById("tbSearchResults");
while(tableBody.childNodes.length > 0) {
tableBody.removeChild(tableBody.childNodes[0]);
}
}
//function show search results in a table
//dynamically creating table rows for show the results
function showResults() {
//debugger;
if(xmlHttp.readyState == 4)
{
if(xmlHttp.status == 200)
{
var results = xmlHttp.responseXML;
var Empid = "";
var companyname = "";
var ContactName = "";
var EmpName = results.getElementsByTagName("Emp");
if(EmpName.length < 1)
return;
//add header of the search table
addHeader();
//dynamically add search results in a table
for(var i = 0; i < EmpName.length; i++) {
Empid = results.getElementsByTagName("EmpID")[i].firstChild.data;
companyname = results.getElementsByTagName("CompanyName")[i].firstChild.data;
ContactName = results.getElementsByTagName("ContactName")[i].firstChild.data;
//creating new table row
addTableRow(Empid, companyname, ContactName);
}
document.getElementById("tblSearchResults").setAttribute("border", "1");
document.getElementById("tblSearchResults").setAttribute("class", "searchtable");
}
}
}
//function for creating new table row
function addTableRow(Empid, companyname, ContactName) {
var row = document.createElement("tr");
var cell = createCellWithText(Empid);
row.appendChild(cell);
cell = createCellWithText(companyname);
row.appendChild(cell);
cell = createCellWithText(ContactName);
row.appendChild(cell);
document.getElementById("tbSearchResults").appendChild(row);
}
//function for create a cell with text
function createCellWithText(text) {
var cell = document.createElement("td");
var textNode = document.createTextNode(text);
cell.appendChild(textNode);
return cell;
}
//add headers of the search result table
function addHeader() {
var row = document.createElement("tr");
var cell = createCellWithText("EmpID");
row.appendChild(cell);
cell = createCellWithText("CompanyName");
row.appendChild(cell);
cell = createCellWithText("ContactName");
row.appendChild(cell);
document.getElementById("tbSearchResults").appendChild(row);
}
</script>
</head>
<body>
<form id="Form1" method="post" runat="server">
<b>Search For Books</b> <span id="header"></span>
<table width="500" border="0">
<tbody>
<tr>
<td>
Search</td>
<td>
<input type="text" onkeyup="NetProgrammingSearch(this.value);" size="40">
</td>
</tr>
<tr>
<td colspan="2">
<table id="tblSearchResults" width="100%" border="0">
<tbody id="tbSearchResults">
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</form>
</body>
</html>
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Search.aspx.cs" Inherits="Search" %> <!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>Untitled Page</title> <script type="text/javascript"> //global variable for hold XMLHttpRequest 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 { //it will work if IE have JavaScript version 5.0 xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch(oc) { xmlHttp = null; } } //Creating object of XMLHTTP for non-IE browsers if(!xmlHttp && typeof XMLHttpRequest != "undefined") { xmlHttp = new XMLHttpRequest(); } } //function to search function NetProgrammingSearch(searchText) { //create XMLHttpRequest Object CreateXmlHttp(); //Requested url var ajaxRequest = "http://localhost/NetProgrammingSearch/Search.aspx?search=" + searchText; //set callback function xmlHttp.onreadystatechange = callBackMethod; //Initializes request xmlHttp.open("GET", ajaxRequest, true); //send request xmlHttp.send(null); } function callBackMethod() { //if request completed sucessfully clear the previous result and show the new search results if(xmlHttp.readyState == 4) { if(xmlHttp.status == 200) { clearResults(); showResults(); } } } //function clear previous results function clearResults() { var tableBody = document.getElementById("tbSearchResults"); while(tableBody.childNodes.length > 0) { tableBody.removeChild(tableBody.childNodes[0]); } } //function show search results in a table //dynamically creating table rows for show the results function showResults() { //debugger; if(xmlHttp.readyState == 4) { if(xmlHttp.status == 200) { var results = xmlHttp.responseXML; var Empid = ""; var companyname = ""; var ContactName = ""; var EmpName = results.getElementsByTagName("Emp"); if(EmpName.length < 1) return; //add header of the search table addHeader(); //dynamically add search results in a table for(var i = 0; i < EmpName.length; i++) { Empid = results.getElementsByTagName("EmpID")[i].firstChild.data; companyname = results.getElementsByTagName("CompanyName")[i].firstChild.data; ContactName = results.getElementsByTagName("ContactName")[i].firstChild.data; //creating new table row addTableRow(Empid, companyname, ContactName); } document.getElementById("tblSearchResults").setAttribute("border", "1"); document.getElementById("tblSearchResults").setAttribute("class", "searchtable"); } } } //function for creating new table row function addTableRow(Empid, companyname, ContactName) { var row = document.createElement("tr"); var cell = createCellWithText(Empid); row.appendChild(cell); cell = createCellWithText(companyname); row.appendChild(cell); cell = createCellWithText(ContactName); row.appendChild(cell); document.getElementById("tbSearchResults").appendChild(row); } //function for create a cell with text function createCellWithText(text) { var cell = document.createElement("td"); var textNode = document.createTextNode(text); cell.appendChild(textNode); return cell; } //add headers of the search result table function addHeader() { var row = document.createElement("tr"); var cell = createCellWithText("EmpID"); row.appendChild(cell); cell = createCellWithText("CompanyName"); row.appendChild(cell); cell = createCellWithText("ContactName"); row.appendChild(cell); document.getElementById("tbSearchResults").appendChild(row); } </script> </head> <body> <form id="Form1" method="post" runat="server"> <b>Search For Books</b> <span id="header"></span> <table width="500" border="0"> <tbody> <tr> <td> Search</td> <td> <input type="text" onkeyup="NetProgrammingSearch(this.value);" size="40"> </td> </tr> <tr> <td colspan="2"> <table id="tblSearchResults" width="100%" border="0"> <tbody id="tbSearchResults"> </tbody> </table> </td> </tr> </tbody> </table> </form> </body> </html> |
In Search.aspx.cs,
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string search = Request["search"];
if (search.Length > 0)
{
Response.Clear();
DataSet dsResults = new DataSet();
//call business layer method for search results
dsResults = getvalue(search);
Response.Clear();
Response.ContentType = "text/xml";
Response.Charset = "utf-8";
string resultsString = dsResults.GetXml();
Response.Write(resultsString);
//end the response
Response.End();
}
else
{
//clears the response written into the buffer and end the response.
Response.Clear();
Response.End();
}
}
else
{
//clears the response written into the buffer and end the response.
Response.Clear();
Response.End();
}
}
private DataSet getvalue(string s)
{
SqlConnection con = new SqlConnection("server=(local);database=northwind;uid=sa;pwd=""");
SqlDataAdapter da = new SqlDataAdapter("select * from EmpName where Empid like '%" + s + "%'", con);
DataSet ds = new DataSet();
da.Fill(ds,"Emp");
return ds;
}
}
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.SqlClient; public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string search = Request["search"]; if (search.Length > 0) { Response.Clear(); DataSet dsResults = new DataSet(); //call business layer method for search results dsResults = getvalue(search); Response.Clear(); Response.ContentType = "text/xml"; Response.Charset = "utf-8"; string resultsString = dsResults.GetXml(); Response.Write(resultsString); //end the response Response.End(); } else { //clears the response written into the buffer and end the response. Response.Clear(); Response.End(); } } else { //clears the response written into the buffer and end the response. Response.Clear(); Response.End(); } } private DataSet getvalue(string s) { SqlConnection con = new SqlConnection("server=(local);database=northwind;uid=sa;pwd="""); SqlDataAdapter da = new SqlDataAdapter("select * from EmpName where Empid like '%" + s + "%'", con); DataSet ds = new DataSet(); da.Fill(ds,"Emp"); return ds; } } |
Conclusion:
Hope this helps,
Happy Coding.