Broadcasting website data using SignalR in MVC

December 19, 2015 Leave a comment

SignalR is a cool API in dotnet framework which you can use to show real time data in your application. You can broadcast real time data to all the connected clients(browsers) once data is ready on server side.

It generates javascripts when rendering on the client side. But you don’t have to worry about all the proxy javascripts as signalR takes care of all those things. All you have to do is just call your javascript function from the server side.

To add signalR in your project go to Nuget Package Manager and search for signalR , you will  see Microsoft ASP.NET SignalR at the top of the list just click install. It will add all the references required to run it. If your project doesn’t have a Scripts folder it will add a Scripts folder and import jquery and jquery-signalR libraries.

At this stage you’ve got all the required references and scripts now its time to add the SignalR startup class so we can tell the OWIN so it can configure it.

Startup class is like;

using Microsoft.Owin;
using Owin;

[assembly: OwinStartupAttribute(typeof(DeepASP.SignalRMVC.SignalRStartup))]
namespace DeepASP.SignalRMVC
public partial class SignalRStartup
public void Configuration(IAppBuilder app)

I added this startup class in App_Start folder as MVC has already created this folder with the startup classes. But you can keep wherever you want. Now add the SignalR Hub class. If you right click and add new item it should be under signalR templates but if it is not, don’t worry just add a new class and inherit it from abstract class–


Lets name this class as “SignalRHub”. You can name anything but just remember this is the hub which you will use in the javascript side. Although you can change the display name by decorating this class with attribute


This class looks like;

namespace DeepASP.SignalRMVC
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
public class SignalRHub : Hub
{ }

Logically that’s all you needed for signalR. Now you want to access the Hub so you can call javascript function from server side, right? YES. OK lets add another class Broadcast.cs as;

namespace DeepASP.SignalRMVC
    using Microsoft.AspNet.SignalR;
    using System;

    public class Broadcast
        private static Lazy<IHubContext> context = new Lazy<IHubContext>(() => GlobalHost.ConnectionManager.GetHubContext<SignalRHub>());

        private static IHubContext Broadcaster
                return context.Value;

        public static bool SendDataToAllConnectedClients(string data)
            return true;

SendDataToAllConnectedClients method calls javascript function “JavaScriptFunction” passing a string parameter. You can pass as many complex objects in JSON format as you want. Just for clarity I call the javascript side function name as JavascriptFunction but you will give a meaningful and purposeful name. Now we will write this javascript function. Like for this post I created another controller called BroadcastController.cs and its view. Now as because this view will be responsible for broadcasting the message sent from server we will add the required .js libraries in this view:

<script src="~/Scripts/jquery-2.1.4.js"></script>
<script src="~/Scripts/jquery.signalR-2.2.0.js"></script>
<script src="~/signalr/hubs"></script> 
var broadcaster = $.connection.Broadcaster; 
broadcaster.client.JavaScriptFunction = function (d) { 
   document.getElementById("data").innerHTML = d; 

Order of javascript libraries DOES matter. Now this is where we are subscribing the javascript function “JavaScriptFunction” which we are calling from server side. For this demo I was just sending a string html from server side but you can write your logic for this function here when you are subscribing.

Yep that’s all signalR is about. If you are interested in downloading this demo just click here.

Well here are some important things to remember before you going to move into production.

Pre-requisites of SignalR2:

  • Dotnet Framework 4.5
  • The user for which Application (IIS) is running must have full trust
  • IIS must be running in Managed mode NOT  Classic.
  • IIS 7 or greater (Websocket requires IIS8)
  • jQuery version must be greater  than 1.6

If you want more control on server side then you might want to look into this

Well here are some of the cool articles I came across while researching some of the issues when I was working on my signalR project;

Categories: features

Dynamically Creating and Showing Bootstrap Modal

October 18, 2015 Leave a comment

Yes I do agree Bootstrap is very cool. Well at-least for a developer you don’t have to mess with a lot of css figuring out responsiveness mobile friendly and a cool design. There may be a lot of other reasons for you to like it but personally I like it because it is now a fully matured framework and also you get a very active community for help.

And recently I was using bootstrap’s Modal quite heavily. So I had to write a lot code in javascript and during the process also wrote this small piece of code to create and show bootstrap modal at run-time in javascript having dynamic title, body and buttons. Thought to share here if anyone needs, though most of us may have already in our code repositories but still no harm in sharing right :).
OK, here are some details about these functions;

 BstrapModal function (title, body, buttons) 

BstrapModal class has a single constructor which takes these three parameters title, body and buttons.

  • Title:Title of the Modal. It can be both html or simple string.
  • Body: Body of the Modal. It can also be html or string.
  • Buttons: Buttons in the footer of the Modal. It is an array of the Button Object. Button object should have Value, Css and Callback function of the button. Value is just the display text of the button while Callback function would be executed on clicking the button. e.g. a button object would look like this
     {Value:"CLOSE", Css:"btn-danger", 
    Callback:function(event){/*Close button click logic*/ }} 

    BstrapModal.Close will close the modal and delete it from document.

    You can extend this class with your requirements. e.g. For different bootstrap button types you can create an enum and put in the constructor. Or you can extend show function so it can get the modal type like large or small etc.

    var BstrapModal = function (title, body, buttons) {
        var title = title || "Lorem Ipsum History", body = body || "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.", buttons = buttons || [{ Value: "CLOSE", Css: "btn-primary", Callback: function (event) { BstrapModal.Close(); } }];
        var GetModalStructure = function () {
            var that = this;
            that.Id = BstrapModal.Id = Math.random();
            var buttonshtml = "";
            for (var i = 0; i < buttons.length; i++) {
                buttonshtml += "<button type='button' class='btn " + (buttons[i].Css||"") + "' name='btn" + that.Id + "'>" + (buttons[i].Value||"CLOSE") + "</button>";
            return "<div class='modal fade' name='dynamiccustommodal' id='" + that.Id + "' tabindex='-1' role='dialog' data-backdrop='static' data-keyboard='false' aria-labelledby='" + that.Id + "Label'><div class='modal-dialog'><div class='modal-content'><div class='modal-header'><button type='button' class='close modal-white-close' onclick='BstrapModal.Close()'><span aria-hidden='true'>&times;</span></button><h4 class='modal-title'>" + title + "</h4></div><div class='modal-body'><div class='row'><div class='col-xs-12 col-md-12 col-sm-12 col-lg-12'>" + body + "</div></div></div><div class='modal-footer bg-default'><div class='col-xs-12 col-sm-12 col-lg-12'>" + buttonshtml + "</div></div></div></div></div>";
        BstrapModal.Delete = function () {
            var modals = document.getElementsByName("dynamiccustommodal");
            if (modals.length > 0) document.body.removeChild(modals[0]);
        BstrapModal.Close = function () {
        this.Show = function () {
            var btns = document.querySelectorAll("button[name='btn" + BstrapModal.Id + "']");
            for (var i = 0; i < btns.length; i++) {
                btns[i].addEventListener("click", buttons[i].Callback || BstrapModal.Close);

    You can use this as;

        new BstrapModal().Show();

    This will show you the below modal, as we didn’t pass any title, body and buttons array, so it will use all default values;

    I used Bootstrap v3.3.5 as you can see in this screen-cast from my project;

HTML to PDF in ASP.Net

March 8, 2015 Leave a comment

In this post I am going to show you how can we easily import html into pdf in without compromising UI. I was looking for an alternative of crystal reports in to generate reports without any javascript burden and complexities in developing them.

As crystal reports gives you the feature to import the report into pdf or excel. So I did some research for libraries for these file formats. Most programming folks were recommending for ITextSharp.

I knew and had used ITextSharp for pdf merge in a project. But when I tried to use this for html to pdf I didn’t get the result I wanted and there were a lot of workarounds needed to get all my requirements.

So I looked for some other solutions and fortunately I found this amazing free library NReco. Which by the way is a wrapper library in .net for this wonderful html to pdf exe wkhtmltopdf.

Before going into detail I’d like to mention my requirements when I was working on html to pdf import on a project. So it would be easier for you if it matches your requirements as well.


  • Same PDF page as its showing on browser
  • Show Background-color
  • Repeat header on every page
  • Show page number on every page
  • Page number count on every page
  • Show images
  • Option to change page orientation (Landscape, Portrait)
  • Free library
  • Support css

Issues I encountered and resolved.

  • Header overlaps when repeating on other pages
  • Page number
  • deploying on 32bit OS.

I’ve attached the link of a sample solution at the end of source codes.

Example code;

/// <summary>
/// Converts html into PDF using nReco dll and wkhtmltopdf.exe.
/// </summary>        
private byte[] ConvertHtmlToPDF()
   HtmlToPdfConverter nRecohtmltoPdfObj = new HtmlToPdfConverter();
   nRecohtmltoPdfObj.Orientation = PageOrientation.Portrait;
   nRecohtmltoPdfObj.PageFooterHtml = CreatePDFFooter();
   nRecohtmltoPdfObj.CustomWkHtmlArgs = "--margin-top 35 --header-spacing 0 --margin-left 0 --margin-right 0";            
   return nRecohtmltoPdfObj.GeneratePdf(CreatePDFScript() + ShowHtml() + "</body></html>");

Html string sample;

        /// <summary>
        /// Returns HTML string.
        /// </summary>
        /// <remarks>Its test data. You can create html using data getting from database or whatever your data source.</remarks>
        /// <returns></returns>
        public string ShowHtml()
            StringBuilder html = new StringBuilder("<table id=\"tblReport\" cellspacing=\"0\" cellpadding=\"0\" style=\"border-width: 0px; border-collapse: collapse; font-family: Tahoma; font-size: 11px; table-layout: fixed; line-height: 20px;\">" +
            "<thead>" +
                "<tr style=\"background-color: #4862A3; font-family: verdana; color: white;\">" +
                    "<th style=\"width: 200px;  text-align: center;\">Name</th>           " +
                    "<th style=\"width: 150px; text-align: center;\">Date Published</th> " +
                    "<th style=\"width: 200px;  text-align: center;\">Category</th>     " +
                    "<th style=\"width: 100px; text-align: center;\">Popularity</th>     " +
                "</tr>" +
            "</thead>" +
            "<tbody>" +
                "<tr>" +
                    "<th style=\"width: 200px; text-align: left; text-align: center;\">Domain Driven Design</th>" +
                    "<th style=\"width: 150px; text-align: left; text-align: center;\">02/05/2011</th>          " +
                    "<th style=\"width: 200px; text-align: center; text-align: center;\">Design Patterns</th>   " +
                    "<th style=\"width: 100px; text-align: left; text-align: center;\">6 out of 10</th>         " +
                "</tr>" +
                "<tr>" +
                    "<th style=\"width: 200px; text-align: left; text-align: center;\">When Not to use jQuery</th> " +
                    "<th style=\"width: 150px; text-align: left; text-align: center;\">02/05/2011</th>             " +
                    "<th style=\"width: 200px; text-align: center; text-align: center;\">jQuery in ASP.Net</th>    " +
                    "<th style=\"width: 100px; text-align: left; text-align: center;\">8 out of 10</th>            " +
                "</tr>" +
                "<tr>" +
                    "<th style=\"width: 200px; text-align: left; text-align: center;\">Programmer's evolution</th> " +
                    "<th style=\"width: 150px; text-align: left; text-align: center;\">02/05/2011</th>             " +
                    "<th style=\"width: 200px; text-align: center; text-align: center;\">General Programming</th>  " +
                    "<th style=\"width: 100px; text-align: left; text-align: center;\">4 out of 10</th>            " +
            for (int i = 0; i < 150; i++)
                html.Append("<tr>" +
                    "<th style=\"width: 200px; text-align: left; text-align: center;\">Test Data</th> " +
                    "<th style=\"width: 150px; text-align: left; text-align: center;\">02/05/2011</th>             " +
                    "<th style=\"width: 200px; text-align: center; text-align: center;\">import html to pdf in</th>  " +
                    "<th style=\"width: 100px; text-align: left; text-align: center;\">4 out of 10</th>            " +
            return html.ToString();

Creat Page number on every page with count.

private string CreatePDFScript()
            return "<html><head><style>td,th{line-height:20px;} tr { page-break-inside: avoid }</style><script>function subst() {var vars={};var'&');for(var i in x) {var z=x[i].split('=',2);vars[z[0]] = unescape(z[1]);}" +
            "var x=['frompage','topage','page','webpage','section','subsection','subsubsection'];for(var i in x) {var y = document.getElementsByClassName(x[i]);" +
            "for(var j=0; j<y.length; ++j) y[j].textContent = vars[x[i]];}}</script></head><body onload=\"subst()\">";

Below image is a snap of the source code. You can download sample solution here.

Handling DBNull.Value

October 20, 2014 2 comments

Every developer use DbNull.Value when writing code to communicate with database. But it could sometimes be quite painful when you want to write with a null-coalescing or ?: operator. The same would be when getting something from database and type checking.

For example in this code snippet I wrote a function which stores a comment in database. As userWebsite is an optional parameter so it could be null and if database expects null then you need to send DBNull.Value. To make it adjustable in ?: operator you just have to cast into an object. like;
Value = userWebsite != null ? userWebsite : (object)DBNull.Value.
I tested this code in fw 4.0 only, so I’m not sure about older versions.

internal int SaveComment(string name, string email, string comment, string? userWebsite)
            SqlCommand _command = new SqlCommand
                Connection = new SqlConnection { ConnectionString = "connection string" },
                CommandType = CommandType.StoredProcedure,
                CommandText = "csp_comment_save",
            _command.Parameters.AddRange(new SqlParameter[] { new SqlParameter { ParameterName = "name", Value = name, SqlDbType = SqlDbType.VarChar, Size = 100 },
            new SqlParameter { ParameterName = "email", Value = email, SqlDbType = SqlDbType.VarChar, Size = 50 },
            new SqlParameter { ParameterName = "comment", Value = comment, SqlDbType = SqlDbType.VarChar, Size = 255 },
            new SqlParameter { ParameterName = "website", Value = userWebsite != null ? userWebsite : (object)DBNull.Value, SqlDbType = SqlDbType.VarChar, Size = 20 }});
            int result=_command.ExecuteNonQuery();
            return result;

WCF RESTful service hosting on IIS6 and consuming by jQuery

July 18, 2014 Leave a comment

Couple of days ago I needed to deploy a WCF RESTfull service on IIS6. Before then I never deployed RESTfull service on IIS6 so it came up with quite configurations for me. While I was deploying this web service on IIS6, I as usual goggled for some configuration related help, although I found, but most of the stuff were scattered. I mean I didn’t find all in a single post or a blog. So I thought why couldn’t do it.

In this post I developed a WCF RESTfull web service from scratch to hosting on web server and consuming by jQuery ajax. Here is the service contract. You’ll find UriTemplate with both with parameters and without parameter.

 /// <PostedOn></PostedOn>
    /// <PostedBy>Muhammad Hussain</PostedBy>
    [ServiceContract(Name = "DeepASPService", Namespace = "")]    
    interface IDeepASPService
        /// <summary>
        /// Returns all articles from the blog.
        /// </summary>        
        /// <returns></returns>
        [WebGet(UriTemplate = "/GetArticles?blogName={blogName}", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]        
        List<Article> GetAllArticles(string blogName);

        [WebGet(UriTemplate = "/GetTagArticles?tagName={tagName}", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
        List<Article> GetArticlesByTagName(string tagName);

        [WebGet(UriTemplate = "/GetArticle?Id={Id}", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
        Article GetArticleById(string Id);

        [WebGet(UriTemplate = "/SaveArticle?authenticationToken={authenticationToken}&amp;title={title}&amp;body={body}&amp;submittedBy={submittedBy}", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
        bool SaveArticle(string authenticationToken, string title, string body, string submittedBy);

Here is the Service implementing above contract. Most of the operations are only defined and not fully implemented as it didn’t need for this post. GetArticles operation returns a generic list in json format.

    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class DeepASPService : IDeepASPService
        public List<Article> GetAllArticles(string blogName)
            return new List<Article>()
                new Article { Id = Guid.NewGuid(), Name=blogName, Title = "WCF RESTfull web service.", Body = "Html body.", Comments=new List<Comment>()
                    new Comment { Id = Guid.NewGuid(), CommentedOn = DateTime.Now, DisplayName = "", Email="", Replies = null }
                new Article { Id = Guid.NewGuid(), Name=blogName,Title = "WCF RESTfull web service deploying on IIS 6.", Body = "Html body.", Comments=new List<Comment>()
                        new Comment { Id = Guid.NewGuid(), CommentedOn = DateTime.Now, DisplayName = "", Email="", Replies = new List<Comment> ()
                            new Comment { Id = Guid.NewGuid(), CommentedOn = DateTime.Now, DisplayName = "", Email="", Replies =null } 

        public List<Article> GetArticlesByTagName(string tagName)
            throw new NotImplementedException();

        public Article GetArticleById(string Id)
            throw new NotImplementedException();

        public bool SaveArticle(string authenticationToken, string title, string body, string submittedBy)
            if (AuthenticateRequest(authenticationToken))
                //save article 
            return true;

        private bool AuthenticateRequest(string authenticationToken)
            //authentication code
            return true;

In this sample application there are only two data contracts but you can have as many data contracts as you need.

    public class Article
        public Guid Id { get; set; }

        public string Name { get; set; }

        public string Title { get; set; }

        public string Body { get; set; }

        public List<Comment> Comments { get; set; }        
    public class Comment
        public Guid Id { get; set; }

        public string DisplayName { get; set; }

        public string Body { get; set; }

        public DateTime CommentedOn { get; set; }

        public string Email { get; set; }

        public List<Comment> Replies { get; set; }


<%@ ServiceHost Language="C#" Debug="true" Service="Namespace.ServiceName" CodeBehind="ServiceName.cs" Factory="System.ServiceModel.Activation.WebServiceHostFactory"%>



    <compilation debug="true" targetFramework="4.0" />
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
      <service name="Namespace.ServiceName" behaviorConfiguration="ServiceBehavior">
        <endpoint binding="webHttpBinding" contract="Namespace.ServiceInterface"
        <behavior name="ServiceBehavior" >
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="True"/>
        <behavior name="webHttp">
    <modules runAllManagedModulesForAllRequests="true"/>

Now we will host this service on IIS. So here is the step by step procedure;

1-Right click on website go to New

2-Click Create virtual directory(in this sample code I created a virutal directory in an existing website)

3- A wizard screen will come up like;
















4-Click Next

5-In Alias textbox give any name for your service e.g. TestRESTfullService

6-Next and browse the path where your service is e.g. wwwroot\RESTfullWCFService




Now although you have successfully deployed your service on IIS but hereafter configurations are required to run it properly.

1-Right click on the new virtual directory you created(e.g. TestRESTfullService)

2-Go to properties

3-By default this virtual directory will be shown as a website(globe logo will appear before it) so you need to convert this into an application.

4-Click on Create application button as showing at #1 in the below picture. After creating application your service icon will change from globe to gear.


















figure 2

5-Change execute permissions from None to Scripts only like the process 2 in the above picture

6- Click on Configuration button and you’ll see this screen;











7-Click on Insert and you’ll see a small screen like this;






8-Click on Browse and select aspnet_isapi.dll from C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll. If you don’t find v4.0.30319 folder and it means you don’t have dotnet framework 4 full version. So you’ll have to download it from microsoft website and install it. After installation complete you’ll find this so then select it.

9- DO NOT FORGET to uncheck “Verify that file exists” checkbox from the above screen.

10- Now click on Directory Security tab from figure 2.

11- In this Authentication Methods screen you will uncheck “Integrated windows authentication” checkbox.

12- Click OK.

13-Now go to ASP.Net tab from figure 2 and select ASP.Net version : 4.0.30313. (Sometimes a message will appear when version is changed so just press OK).

14- Now restart your IIS. It will lose all sessions of websites hosted on this server so be cautious, its better to do at night time.

14-That’s all you needed.You’ve done it !

Your WCF RESTfull service must be running

Now its time to consume your service. Here we will consume using jQuery ajax like;

function GetAllArticles() {
            var url = "/TestRESTfullService/ServiceName.svc/GetArticles?blogName=deepasp"
            $(function() {
                    type: "GET"
                    url: url,
                    async: true,
                    dataType: "json"
                    success: function(articles) {
                        if (articles != null) {
                            document.getElementById("response").innerHTML = ConvertObjecToHtml(articles);
                            document.getElementById("response").innerHTML ="No articles published yet on this blog."
                    error: function(e) {
                        alert("Error occured while processing service request" + e.responseText);

Here download the source code;

Session Variables Management

June 12, 2014 Leave a comment

Session variables are used in our web applications quite often. Some of the variables are maintained for the whole session. So we can use them in different places to perform application’s logic. But while getting some values errors happen just because of a small silly spelling mistake and application blows up. We can somehow overcome most of the common session variables spelling mistake problems by using static classes. Because in this way you don’t need to spell each time you access.

In this post I created a static class in Web/UI layer and created properties for all those common session variables used by our application. So in this way you can set or get your session variables just using this class. It also serves you to organize your session variables in your project.
As it is only a class so I captured it in an image, but if you need source code it can be provided.

 /// <summary>
    /// Managing Session Variables
    /// </summary>
    internal static class BlogSessionVariables
        /// <summary>
        /// Gets sets UserIdentification variable.
        /// </summary>
        public static string UserIdentifier
            get { return (HttpContext.Current.Session["UserIdentification"] != null ? Convert.ToString(HttpContext.Current.Session["UserIdentification"]) : string.Empty); }
            set { HttpContext.Current.Session["UserIdentification"] = value; }

        /// <summary>
        /// Gets sets articles variable.
        /// </summary>
        public static List<dynamic> Articles
            get { return (HttpContext.Current.Session["Articles"] != null ? (List<dynamic>)HttpContext.Current.Session["Articles"] : null); }
            set { HttpContext.Current.Session["Articles"] = value; }

Click the image to enlarge so you can view the whole class and test functions.
session variable management

Pure JavaScript Autocomplete in ASP Classic

May 21, 2014 4 comments

In this post I implemented auto-suggestion using pure JavaScript. Although if you wanna use jQuery autocomplete you can use it. But if you are only using for this purpose then I would recommend not to use jQuery.

Firstly they are large files which will obviously affect your application’s performance. Secondly it is little slower in DOM traversing than pure JavaScript. Thirdly you can easily change JavaScript code, as you don’t necessarily need to have high level expertise in JavaScript.
In addition to that sometimes it has browser compatibility issues as well. So always try to use more standard and basic way in your programming. At least that’s my practice.

I implemented this JavaScript Autocomplete using ASP Classic as a server side language. But you can use any other language. I tried to make it as simple as possible but you can still make it more simple because there’s always a room for better.

This is the html:

 <input type="text" id="txtSearchEngines" class="data">
 <div id="suggestionBox" style="display:none">sss</div>

CSS classes:

    position: absolute;
    border:01 gray solid;
    width: 300px;    
    font-family: Tahoma;

Here’s the JavaScript Code:

var request,xmlhttp,rowToSelect = 0,searchTextBox = document.getElementById("txtSearchEngines"),
function BindSearchTextBox(){
	searchTextBox.addEventListener("keyup", KeyUpOnSearchTextBox,false);
function KeyUpOnSearchTextBox(e){
	var suggestBox = document.getElementById("suggestionBox");
	if((e.keyCode >= 65 && e.keyCode <= 90) || (e.keyCode == 40 || e.keyCode == 38 || e.keyCode == 8) ){				
		if((e.keyCode == 40 || e.keyCode == 38 ) && != "none"){    				
			SelectSuggestedRow(e.keyCode == 40 ? 1: -1 );
			if(null != searchTextBox.value && "" != searchTextBox.value) SendAJAXRequestToServer(_URL+"?type=s&searchKey="+searchTextBox.value,ShowSuggestion,true);
			else{ HideSuggestionBox(); BindSearchTextBox();}
	else if(e.keyCode==13){searchTextBox.removeEventListener("keyup",KeyUpOnSearchTextBox); GetSelectedDetail(); }
function ShowSuggestion(){
	if (xmlhttp.readyState == 4) {
		if(xmlhttp.responseText != ""){
    		var suggestBox = document.getElementById("suggestionBox"),suggestRow=document.getElementById("suggest-rows");""; searchTextBox.offsetTop + searchTextBox.offsetHeight+ 02; searchTextBox.offsetLeft;
    		suggestBox.innerHTML = xmlhttp.responseText;   "";	
		else HideSuggestionBox();
function CloseSuggestionBox(e){
	var eObj = e || window.event;
	if("data") == -1) HideSuggestionBox();
function HandleTabKey(e){
	if(e.keyCode == 9) GetSelectedDetail();
	else if(e.keyCode == 27) HideSuggestionBox();
function HideSuggestionBox(){
	var suggestBox = document.getElementById("suggestionBox");
	suggestBox.innerHTML = null; ="none";	
function HoverOverSuggestedList(obj){UnselectRow(); rowToSelect = obj.getAttribute("rowIndex"); SelectRow();}
function SelectRow(){document.getElementById("tblSuggest").rows[rowToSelect].className = "suggest-data rowSelected";}
function SelectedRowClicked(e){GetSelectedDetail();}
function UnselectRow(){	var suggestedTable=document.getElementById("tblSuggest");if(suggestedTable != null) suggestedTable.rows[rowToSelect].className = "suggest-data";}
function SelectSuggestedRow(rowCount){
	if(rowToSelect == 0){ if(rowCount == 1) rowToSelect = rowCount;}
	else rowToSelect = rowToSelect + rowCount;
	if(rowToSelect >= document.getElementById("tblSuggest").rows.length){rowToSelect = rowToSelect - 1;SelectRow();}
	else SelectRow();
function GetSelectedDetail(){
	var suggestedTable=document.getElementById("tblSuggest");
	if(suggestedTable != null){
function SendAJAXRequestToServer(url,handler,ajax){
	xmlhttp= new XMLHttpRequest();'GET', url,ajax);
	xmlhttp.onreadystatechange = handler;

ASP Classic code to return the suggestions for the search key;

'put your security/authenciation code here
response.write GetSuggestion
public Function GetSuggestion
	'Its just a demo you can write your code to get from database.
	dim searchKey 
		searchKey = Request.QueryString("searchKey")
	if(searchKey = "g") then
		GetSuggestion = "<table border='0' cellpadding='0' cellspacing='0' width='100%' id=""tblSuggest""><tr onclick=""SelectedRowClicked(event)"" onmouseover=""HoverOverSuggestedList(this)"" name='suggest-rows' rowIndex=""0"" class='suggest-data data' ><td class=""data"" style=""display:none"">1</td><td class=""data"" align='left' class=""data"">Google</td></tr><tr onmouseover=""HoverOverSuggestedList(this)"" onclick=""SelectedRowClicked(event)"" name='suggest-rows' class='suggest-data data' rowIndex=""2""><td class=""data"" style=""display:none"">3</td><td class=""data"" align='left'>Google2</td></tr></table>"
	else if(searchKey = "b") then
		GetSuggestion = "<table border='0' cellpadding='0' cellspacing='0' width='100%' id=""tblSuggest""><tr onclick=""SelectedRowClicked(event)"" onmouseover=""HoverOverSuggestedList(this)"" name='suggest-rows' class='suggest-data data' rowIndex=""1""><td class=""data"" style=""display:none"">2</td><td class=""data"" align='left'>Bing</td></tr></table>"
	end if
	end if
end function


Get every new post delivered to your Inbox.