Friday, August 24, 2007

SmartNavigation Vs MaintainScrollPositionOnPostback in 2.0

MaintainScrollPositionOnPostback in 2.0

Every one of us know very well about the feature of "SmartNavigation", BUT In Visual studio version 2.0 and above "SmartNavigation" has become obsolete. Now What is the alternate for this, if you want to achieve same feature as "SmartNavigation" then use "MaintainScrollPositionOnPostback".

How to use

Just set Page.MaintainScrollPositionOnPostback = true in page load event and java script will be inserted into your rendered page that maintains the scroll position in the browser window for all post back.
Believe me it's really a good feature in 2.0, it would reduce lots of coding effort to maintain scroll position in web page.

Another alternate to maintain page scroll position

This way is same what we do for HTML documents. The following lines you can write into the server side or client side. Below example to write in server side

StringBuilder maintainScrollPosition = new StringBuilder();

maintainScrollPosition.Append("<script language='javascript'>");
maintainScrollPosition.Append("var pageSize = 722;");
maintainScrollPosition.Append("if (document.frmHome.offsetHeight > pageSize){");
maintainScrollPosition.Append("location.href='#scrollTo" + entity[0] + "';}");

Page.ClientScript.RegisterStartupScript(this.GetType(), "Contents", maintainScrollPosition.ToString());

Here entity[0] has a value where you want to set scroll position, in other word it's a flag.You can assume entity[0] is heading in your aspx page and after postback you want scroll position be on this heading.

Note: Above example also explains how we can write java script in code behind (C#)

Wednesday, August 08, 2007

How to do auto page refresh in ASPX

How to do auto page refresh in ASPX

If you have a requirement something like auto redirect page to login page or auto refresh the current window within 10 sec or auto close window after 10 sec then you can write some lines of code in java script to achieve this

There are multiple ways to auto refresh/auto close browser, some very simple ways are below with examples.

1) Auto page refresh à you can write below code inside <head> tag on top of your ASPX page
<head runat="server">
<meta http-equiv="Refresh" content="10;url=''">
Note: Content takes two parameter 1) <number of second>
2) <URL>

2) Auto page redirect à you can write below code inside <head> tag on top of your ASPX page

<head runat="server">
<meta http-equiv="Refresh" content="10;url='http://localhost/Home/Login.aspx'">
http-equiv="Refresh" à This tag will do page auto refresh
content="<number of second>,<URL>" à action when page refresh

3) Auto new page open à If you want to open new window after 10 sec then you can create a java script function say "OpenNewWindow" and use this function like below

<head runat="server">
<meta http-equiv="Refresh" content="10;url='javascript: OpenNewWindow('http://localhost/Home/Login.aspx',650,1000)">

Note: content="<number of second>,<URL>" , 650 =height 1000= width.

function OpenNewWindow(url, h, w)
{,"","width=" + w + ",height=" + h + ",scrollbars=yes,resizable=yes,toolbar=yes,menubar=yes,location=yes,

4) Auto page close à if you want to close the browser after 10 sec then write below code on top of your ASPX page
<script language="JavaScript">
var timestamp= 10;
window.opener = top;
<script language="JavaScript">

Friday, August 03, 2007

How to use AJAX in DOTNET web applications

How to use AJAX in DOTNET web applications


This document is useful for creating web application using AJAX. This document explain what is Ajax, how to use with sample source code in

This document covers the following

1) How to create web application using Ajax
2) How to call server side method from JavaScript
3) How to fetch data from database without taking client side round trip
4) From where to download AJAX framework


ASP.NET AJAX is a framework for creating a new generation of more efficient, more interactive and highly-personalized Web application that work across most of browsers.
What you can do with ASP.NET AJAX:

ü Access remote services and data directly from the browser without writing complicated script.
ü Create next-generation interfaces with reusable AJAX components.
ü Enhance existing Web pages using powerful AJAX controls. Continue using Visual Studio 2005.

Download center

You can download AJAX framework from

Sample Source code

In the Web application if we want to get data from the server we have to do server trip to execute code behind function that execute stored procedure/query to fetch/delete/update the data from the database.

server trip is always very heavy operation in the web application. Now using Ajax we can avoid client side server trip and without client side server trip we can get the data in the client side.

AJAX is nothing like magic; it is a way to call server side methods from JavaScript.
Ajax.NET is good for lightweight remote calls using JavaScript.

Let say you have a requirement where if you type any text in the text box corresponding data should display in the table, this is kind of searching related data as when you type any text in the text box.

Below I am giving one example code "How to fetch data from database using AJAX call"

Follow the steps to create Web Application

1) Create one Aspx page name "GetUser.aspx"

a) Create one private method in this page say "GetUsernameListFromDB"
private void GetUsernameListFromDB()
string conn = "Data Source= DBServer;Initial Catalog=DBNAme;
User Id= UID;Password= PWD";
//Get the request query
string whereCondition = Request["Condition"].ToString();
string sqlQuery = "select FName,Lname,DOB from Employee
where FName like '" + whereCondition + "%'";
DataSet ds = new DataSet();
ds = SqlHelper.ExecuteDataset(conn,CommandType.Text, sqlQuery);
StringBuilder strXml = new StringBuilder();
strXml.Append("<table border='1' width='100%'
height='100%' cellpadding='2' cellspacing='2'>");
strXml.Append("<tr bgcolor='skyblue'>
<td>First Name </td><td>Last Name</td>
<td>Date of Birth</td></tr>");
//Create Html Table runtime
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
strXml.Append("<td>" + ds.Tables[0].Rows[i][j].
ToString() + "</td>");
// This is for to retain the value when page get referesh
Session["XMLData"] = strXml;
//write response data in the page

b) Call above method in the page load event of "GetUser.aspx.cs" page

protected void Page_Load(object sender, EventArgs e)

2) Create another Aspx page name "Default.aspx"

a) Screen shot

b) Design Source code

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="" >

<head runat="server">
<title>Getting Data from Database using AJAX Call</title>


var xmlHttp;
var requestURL = 'http://localhost/AjaxExample/GetUser.aspx?Condition=';
var is_ie = (navigator.userAgent.indexOf('MSIE') >= 0) ? 1 : 0;
var is_ie5 = (navigator.appVersion.indexOf("MSIE 5.5")!=-1) ? 1 : 0;
var is_opera
= ((navigator.userAgent.indexOf("Opera6")!=-1)
(navigator.userAgent.indexOf("Opera/6")!=-1)) ? 1 : 0;
//netscape, safari, mozilla behave the same???
var is_netscape
=(navigator.userAgent.indexOf('Netscape') >= 0) ? 1 : 0;

function Display_Data(strName)
if (strName.length > 0)
//Append the name to search for to the requestURL
var url = requestURL + strName;
//Create the xmlHttp object to use in the request //stateChangeHandler will fire when the state has changed, i.e. data is received back
// This is non-blocking (asynchronous)
xmlHttp = GetXmlHttpObject(stateChangeHandler);
//Send the xmlHttp get to the specified url
xmlHttp_Get(xmlHttp, url);
//Textbox blanked out, clear the results
document.getElementById('RelatedDataList').innerHTML = '';

//stateChangeHandler will fire when the state has changed, i.e. data is received back, This is non-blocking (asynchronous)
function stateChangeHandler()
//readyState of 4 or 'complete' represents that data has been returned
if (xmlHttp.readyState == 4 xmlHttp.readyState == 'complete')

//Gather the results from the callback
var str = xmlHttp.responseText;
//Populate the innerHTML of the div with the results
if (document.getElementById)
//This indirecting writing into the panel require for IE
var t = document.createElement('div');
t.innerHTML = str;
document.getElementById('RelatedDataList').innerHTML = "";
else if (document.all)
document.all['RelatedDataList'].innerHTML = xmlHttp.responseText;
else if (document.layers)
document.layers['RelatedDataList'].innerHTML = xmlHttp.responseText;

// XMLHttp send GET request
function xmlHttp_Get(xmlhttp, url)
{'GET', url, true);
function GetXmlHttpObject(handler)
var objXmlHttp = null;
//Holds the local xmlHTTP object instance
//Depending on the browser, try to create the xmlHttp object
if (is_ie)
//The object to create depends on version of IE
//If it isn't ie5, then default to the Msxml2.XMLHTTP object
var strObjName = (is_ie5) ? 'Microsoft.XMLHTTP' : 'Msxml2.XMLHTTP';
// create the object
objXmlHttp = new ActiveXObject(strObjName);
objXmlHttp.onreadystatechange = handler;
//Object creation errored
alert('IE detected, but object could not be created. Verify that
active scripting and activeX controls are enabled');
else if (is_opera)
//Opera has some issues with xmlHttp object functionality
alert('Opera detected. The page may not behave as expected.');
// Mozilla Netscape Safari
objXmlHttp = new XMLHttpRequest();
objXmlHttp.onload = handler;
objXmlHttp.onerror = handler;
//Return the instantiated object
return objXmlHttp;

function UseValue(strVal)
document.frmDefault.txtName.value = strVal;

<form name="frmDefault" id="Form1" runat="server">
<table border="0" cellpadding="4" cellspacing="0" id="Table2" >
<td width="100">Name:</td>
<input type="text" name="txtName" id="txtName" autocomplete="off" onkeyup="Display_Data(txtName.value);">
<td width="100" valign="top">Related Data:</td>
<div id="RelatedDataList" runat="server"></div>

c) Code behind (Default.aspx.cs)

public partial class _Default : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)
// This require when you need to persist the data after referesh
if (Session["XMLData"] != null)
RelatedDataList.InnerHtml = Session["XMLData"].ToString();


d) Run the application and type some text in the "Name" text box

As when you type any text in the "Name" text box without getting server trip for client it display filter data in to the screen.

How this page works internally

1) When you type any text into the textbox onkeyup events of textbox calls JavaScript function "Display_Data(txtName.value);" This function internally points to "GetUser.aspx" page in the form of http module 'http://localhost/AjaxExample/GetUser.aspx?Condition ='

2) And based on QueryString parameter "GetUser.aspx" page_Load calls perticular method "GetUsernameListFromDB()", This method take the parameter and get the data from database and generate html table structure on server side and return (html) result to page using "Response.write(strXml)"

3) Yes, It does server trip but it's happen parallel in server side it's not visible to client page, client page does not refresh in this whole process that why we can say without client side post back we can call code behind method using AJAX.


Ø Input from devices such as microphones, webcams, and gamepads; output to devices like printers and portable gadgets.
Ø Playing music and sound effects.
Ø Adding buttons, toolbars, bookmarks, icons; changing browser behavior.
Ø Reading and writing files on the user's hard drive.
Ø Catching events such as shutdown initiation; changing preferences; popping up alerts; reading hardware information.
Ø Providing a full range of keyboard shortcuts while avoiding conflicts with the browser's own keyboard shortcuts.