In a previous article, we looked at Master Pages in ASP.NET 2.0. Master pages allow you to dictate the layout and common content for the pages in your application using template files with a .master extension. The Themes feature in ASP.NET 2.0 allows you to dictate the appearance of controls in your application using template files with a .skin extension, and with style sheets. In this article, we will examine the Themes feature in-depth.
There is some overlap in what you can do with themes and master pages, as we will see later in the article. What you ultimately can achieve with the combination of these two features is the following:
  • Easily build a web application with consistent layout and appearance across all pages
  • Easily change the layout and appearance of all pages just by modifying a few template files
  • Easily personalize an application at run time for a specific user by letting the user chose their favorite look from a number of appearance and layout options
    Let’s get started understanding how themes work with a simple example.

    Creating A Theme

    Themes, unlike master page files, need to live underneath a special directory by the name of App_Themes. Visual Studio will add an App_Themes folder to a web application when you right click the web project, select Add Folder from the context menu, and select the Theme folder item.
    Also unlike master pages (which are single files), themes consist of a collection of files. A theme may contain .skin files, style sheets, and even image files. To organize and name themes, we use subfolders in App_Themes. In the following screen shot, we have a theme by the name of “Odeish” and a theme by the name of “Codeish”.
    Inside of our Odeish folder we will create a .skin file. You can add as many .skin files to a theme as you need. Each skin file will contain one or more control skins. A control skin specifies the property settings to apply to a specific type of control.
    In our example, we will create a skin file with the name of Calendar.skin. Although our skin file will only contain the control skin for a single type of control – the Calendar control, we could take a different approach and add all the control skins for a theme inside of a single skin file. In this case our Calendar.skin file will contain the following.
    <asp:Calendar runat="server" BackColor="White"
                  BorderColor="#3366CC" BorderWidth="1px" CellPadding="1"
                  DayNameFormat="Shortest" Font-Names="Verdana" Font-Size="8pt"
                  ForeColor="#003399" Height="200px" Width="220px">
      <SelectedDayStyle BackColor="#009999" Font-Bold="True"
                        ForeColor="#CCFF99" />
      <SelectorStyle BackColor="#99CCCC" ForeColor="#336666" />
      <WeekendDayStyle BackColor="#CCCCFF" />
      <OtherMonthDayStyle ForeColor="#999999" />
      <TodayDayStyle BackColor="#99CCCC" ForeColor="White" />
      <NextPrevStyle Font-Size="8pt" ForeColor="#CCCCFF" />
      <DayHeaderStyle BackColor="#99CCCC" ForeColor="#336666" Height="1px" />
      <TitleStyle BackColor="#003399" BorderColor="#3366CC" BorderWidth="1px"
                  Font-Bold="True"
                  Font-Size="10pt" ForeColor="#CCCCFF" Height="25px" />
    </asp:Calendar>
    Notice a control skin looks just like the declaration of a server-side control in an ASPX or ASCX file, with the exception that we don’t set the ID property in the skin. The runtime will apply the property values and styles in this skin to all of the calendar controls on every page using the Odeish theme.
    Here is another example showing the control skin for a server side Label control. We can place this skin inside a second skin file in the Odeish theme by the name of Label.skin. This skin will set all of our Label controls with a BlueViolet ForeColor property.
    <asp:Label runat="server" ForeColor="BlueViolet" />
    You can generally skin any appearance related property on a control, but not all properties. Some properties, like the ID and EnableViewState properties have metadata set to forbid setting the property via a skin (the System.Web.UI.ThemeableAttribute will be present on the property with a value of false). The ThemeableAttribute can also be applied at the class level to mark an entire control as themeable or not. The Repeater control is not themeable because it derives from the Control class which is marked with Themeable=false. Any control deriving from WebControl will have themeing enabled by default.

    Applying A Theme

    There are several ways to apply a theme to your pages. In the following web form we’ve set the theme using the Theme attribute of the @ Page directive.
    <%@ Page Language="C#" AutoEventWireup="true"
            CodeFile="Default.aspx.cs" Inherits="_Default"
            Theme="Odeish" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
              "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>Home</title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:Calendar ID="Calendar1" runat="server" />
                <br />
                <asp:Label ID="Label1" runat="Server" Text="This is a label" />
            </div>
        </form>
    </body>
    </html>
    Even though we have not set any of the display properties on the calendar or label controls, the above web form will render with the colors and styles from our theme, as shown in the next screen shot.
    Note: there is no support in the designer for creating skins (only the text editor), nor for viewing a themed page. The only way to see the end result is to view the page in a browser after a successful build.
    It’s also important to point out that the property value specified by a theme will override any property value in the ASPX markup. For instance, even if we marked our Label control with ForeColor=”Black” in the ASPX markup, the Label would render with a BlueViolet color, because that is the color specified by the theme.
    You can also set themes at the application level using web.config (or at the machine level using machine.config). Use the theme property of the <pages> section as shown below. You can override the configuration setting with the Theme attribute in the @ Page directive.
    <?xml version="1.0"?>
    <configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
        <system.web>

           <pages theme="Odeish" />
           <compilation debug="true"/>
           <authentication mode="Windows"/>

        </system.web>
    </configuration>
    If you are setting themes at the machine level, you’ll want to have themes defined at the machine level. Machine-wide themes need to be located in %WINDIR%\Microsoft.NET\Framework\\Themes.
    We can programmatically set the theme for a page. Like the MasterPageFile setting we discussed in the master page article, the Theme property must be set in the PreInit event of a page. This is because the skins in a theme are applied after the PreInit event fires but before the Init event fires. Later in the article we will take a closer look at how the runtime applies skins.
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_PreInit(object sender, EventArgs e)
        {
            Theme = "Odeish";
        }
    }
    Programmatically setting the theme is useful when you allow users to personalize your site and select their preferred look and feel. You could store a user’s preferred theme in the Profile object of ASP.NET 2.0, and set the theme during the PreInit event of each page they view.
    Now that we’ve seen the basics of how to create and apply themes, we can dig into more details.

    Named Skins

    You can only specify one default control-skin in a theme per control type. In our example, it would not make sense to define a second skin for the Label control in the Odeish theme since we already have a skin defined for Label, and ASP.NET would not know which to use. However, you can specify alternative named skins for a control with the SkinID property.
    In the skin file that follows, we’ve defined the default skin for a label to use a BlueViolet color, while the skin named BlackLabel will use a black forecolor.
    <asp:Label runat="server" ForeColor="BlueViolet" />
    <asp:Label runat="server" ForeColor="Black" SkinID="BlackLabel" />
    Inside of the following web form excerpt, the first label control will use the default control skin (assuming the page’s Theme property is set properly), while the second label control uses the BlackLabel named skin.
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:Label runat="server" ID="label1"
                Text="Hello World" />
            <br />
            <asp:Label runat="server" ID="label2"
                Text="Hello World" SkinID="BlackLabel" />
        </div>
        </form>
    </body>

    Overriding Themes

    Earlier, we mentioned how a skin will overwrite any display properties we set on a control in our ASPX page. There might be times when this is not the desired behavior. One way to avoid the application of skin properties is to disable themeing for a specific control (or for an entire page) by setting the enable themeing property to false.
    <asp:Label runat="server" ID="label1"
               Text="Hello, from OdeToCode"
               ForeColor="Green" EnableTheming="false" /> 
    The EnableThemeing property will cascade through child controls. For instance, if you set EnableThemeing=false on a Panel or user control, any control inside of the panel or user control will not be themed.
    A second way to use individual control properties is by specifying a StyleSheetTheme instead of a Theme. Unlike the properties applied by a Theme, the properties applied by a StyleSheetTheme can be overridden in a page. In the following webform, the first Label will display with the BlueViolet color of the Odeish theme, while the second label will override the skin setting and display with a DarkSalmon color.
    <%@ Page Language="C#" AutoEventWireup="true"
        CodeFile="Default4.aspx.cs" Inherits="Default4"
        StylesheetTheme="Odeish" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
            "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>Untitled Page</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:Label runat="server" ID="label1" Text="Hello World" />
            <asp:Label runat="server" ID="label2" Text="Hello World"
            ForeColor="DarkSalmon"/>
        </div>
        </form>
    </body>
    </html>
    Just to be clear: if we had specified a Theme instead of a StyleSheetTheme, both labels would display with the BlueViolet color. If we were to specify a Theme for our pages in web.config, the web.config Theme setting would override this StyleSheetTheme and both Labels would display in BlueViolet.
    Interesting note: the Visual Studio designer will display the form with the skins applied when a StyleSheetTheme is in effect. The designer does not apply skins when a Theme is in effect.

    Themes and CSS Style Sheets

    Themes and CSS files can work together to control the look of your application. You can add one or more .css files into a theme directory. ASP.NET will automatically apply all of a theme’s style sheets into a page by injecting a <link> element for each .css into the header of a page. Your page must have runat=”server” in the <head%gt; tag for the automatic style sheet inclusion. The pages created by the IDE have this setting automatically.
    For instance, we can control the background color of our page using the following style sheet.
    body{
        background-color:Gray;
    }
    Obviously, style sheets and skins have some overlap. For instance we could use a skin to set the ForeColor of our label, or we could have used a CSS class to set the color of our label text (perhaps by setting the CssClass property of the label with a skin).
    Here are some points to consider when deciding on a skin file versus a style sheet entry.
    • Web designers will be more comfortable with css files. If you put the design of your site into the hands of professionals than you should be asking them to use css wherever possible. This will allow you to just drop new and updated css files into the theme folders and be ready to go.
    • Developers might be more comfortable with skins. Since skins look just like a control declaration, a developer will have an easy time creating a skin file. There is also no need to know in advance what HTML a complex server-side web control will produce in order to write the correct class and styles.
    • Skins are applied server-side and can set more than just style related properties. For example, in our Calendar.skin example we were able to set a default for the DayNameFormat for all calendar controls using the theme.
    • Likewise, you can control some areas with CSS (like the body element above) with style sheets and not skins
    • While the settings in a style sheet cascade, the properties in a skin are absolute, i.e. you can override a style sheet with a local setting but not a skin (unless you take one of the steps outlined in this article).
    • Different browsers may react to style sheets in different ways. You can count on skin files to always apply their properties to controls consistently on the server (it’s up to ASP.NET to translate those settings into the correct settings for the client).

    Themes with Images

    You can also include images in the themes directories. Images inside of themes are particularly useful for controls like the TreeView, and Menu controls that rely on consistent but customizable images to render themselves.
    All you need to do is provide your skin with a relative URL to the image. ASP.NET will take care of fixing up the URLs.

    Under The Hood

    When a request arrives for an ASP.NET 2.0 site, the runtime will parse and compile the App_Themes directory into assemblies. Although we might not think of a theme as being “code” (nor may a theme or skin file actually contain any code) – the runtime does turn each theme definition into code inside an assembly.
    Each assembly will contain a class representing the theme – this class will derive from System.Web.UI.PageTheme. The class will contain a LinkedStyleSheets property that returns an array of string – the filenames for the styles of the theme.
    The class will also maintain a dictionary data structure. The key into the dictionary is a type (like typeof(Label) and typeof(Calendar). Given the key, the dictionary will return a ControlSkinDelegate. The delegate is a pointer to the method that “builds” a control according to the rules in a skin file. For example, the skin file for our label produced the following method.
    private Control __BuildControl__control11(Control ctrl)
    {
          Label label1 = (Label) ctrl;
          label1.ForeColor = Color.BlueViolet;
          return label1;
    }
    When the runtime sees that a page has a theme, it walks through the Controls array of the page and checks to see if there is a delegate available to skin the control based on the type of the control. If an entry exist, the runtime will invoke the delegate, which in the case of a Label in an Odeish page theme will execute the above code.

    Themes and Master Pages

    As we alluded to earlier in the article, there can be some overlap between themes and master pages. In the previous article we actually controlled the layout of our application by defining <div>s in our master page and specifying the layout of the <div>s in a .css file.
    The above approach is a viable approach when using themes. Push your layout defining css into the themes folder for the ultimate power and flexibility. Your master pages will continue to define the basic structural elements and common content for every page.

    AJAX, ‘Old wine in a new bottle’. Puzzled!  Absolutely right. AJAX was with us for a long time, until we realized its true potentials. Lets take a very close example and we use it in our everyday life. Google? Yes, very true. Google was very early mover in AJAX arena and showed the world, web applications close to desktop applications. People were so fascinated with desktop applications that there was an urgent need of such ‘Avatar’.  Suppose you are in the middle of filling a user registration page. You fill all the necessary information and hit the register button. Err..it says “Username already exists. Please try again”. You tried once, twice, thrice and so many times and after page refreshes it is showing the same message. Well, application does not have any choice but to display this error message. But now we can take off the pain and show something interactive, a user may like. Major websites will allow you to enter the username, but at the same time they will be able to tell you if this username has been taken out and without page refresh. That is AJAX. Most close example. Try typing words in Google search box and it will show you an array of suggestions. This is just a tip of iceberg. Believe me, you can create a very rich web based application by allowing AJAX to come into your life.
    Topics We Will Cover
    (1)    What is AJAX
    (2)    Why to use AJAX
    (3)    AJAX nomenclatures
    (4)    AJAX with ASP.NET 4.0 (.NET 4.0 framework is still in beta but a lot to offer)
    (5)    Future of AJAX  
    At the end of the post , you will find the link to download the code for all the examples demonstrated here.
    What is AJAX
    AJAX = Asynchronous JavaScript and XML.
    It is based on JavaScript and HTTP requests.
    You may ask, is this a new programming language? No, it is a new way to use existing standards.  It is a way of creating better, faster and more interactive web applications. AJAXcan directly communicates to the server and without page refresh.  It uses asynchronous data transfer (we say it, HTTP requests) between the browser and web server.  In this tutorial, we will create an application with AJAX support on .NET 4.0 (it is still in beta but a lot to offer). AJAX is all about making rich and user friendly web applications.
    Why to use AJAX
    I am sure, after reading the reasons; you will definitely plan to use AJAX in your web applications. Let’s take a very conventional example of submitting a form to the web server or getting the information of the submitted data.  In the conventional scenario, you fill some form, validate the inputs and submit the form. We wait for the server to respond and new page to load. This way application may run slowly and will have less use friendly experience. Now integrate our ‘Avatar’ in our web application. Our new ‘Avatar’ will directly talk with the server and process the information in the background and it is too fast.  With AJAX we can make or get the request from the server without page reload. AJAX was made popular by Google with its Google suggestion box.  In this tutorial we will develop Google suggestion sort of thing and I am sure once you finish with this tutorial, you will have every reason to use AJAX in your web applications.
    AJAX Nomenclature
    AJAX use the XMLHttpRequest object. By using the XMLHttpRequest object, we can update a page with data from the server after the page has loaded.  ‘Google Suggest’ is using the XMLHttpRequest object to create a very dynamic web experience. When we start typing in Google’s search box, a JavaScript sends the letters off to a server and the server returns a list of suggestions. And good news is The XMLHttpRequest object is supported in all major browsers (Internet Explorer, Firefox, Chrome, Opera, and Safari).  XMLHttpRequest is the core of making AJAX web applications. Let’s examine how it works. Before we move ahead, I expect you are familiar with basic HTML and Javascript. Since AJAX is written in javascript, so have a look at the basic example, how it communicate with the server.
    (1)    <head>
    (2)    <script>
    (3)    function loadXMLDoc(url)
    (4)    {
    (5)    if (window.XMLHttpRequest)
    (6)    {// code for IE7+, Firefox, Chrome, Opera, Safari
    (7)    xmlhttp=new XMLHttpRequest();
    (8)    }
    (9)    else
    (10){// code for IE6, IE5
    (11)xmlhttp=new ActiveXObject(”Microsoft.XMLHTTP”);
    (12)}
    (13)xmlhttp.open(”GET”,url,false);
    (14)xmlhttp.send(null);
    (15)document.getElementById(’suggestion’).innerHTML=xmlhttp.responseText;
    (16)}
    (17)</script>
    (18)</head>
    That’s all we needed to communicate with the server. Now server will obey our instructions and will respond t our requests.  Now let’s understand the above code. As I said earlier, core is XMLHttpRequest and it comes in built with the modern browsers.
    Line 3 is very simple approach to pass an URL with javascript function loadXMLDoc.
    Line 5 detects the browser is being used. There is some tweak, how it behaves with IE7+, Firefox, Chrome, Opera and Safari browser and with IE6 and IE5.  Nothing fancy.
    Line 7 and 9, create and initializes the XMLHttpRequest  object.
    Line 13 open() method takes 3 parameters. First one is the type of communication we want to perform with web server. So if you want to get some data from web server, use ‘GET’ else use ‘POST’.  Second parameter takes the server URL to whom you want to communicate. The third parameter  specifies, if the request should be handled asynchronously. You will stop by and ask, ‘Hey what dose it mean?’. Well, it can have two values. Either true or false.  False tells the XMLHttpRequest object to wait until the server request is completed before next statement is executed.  For small applications and simple server request, this seems to be ok. But if the request takes a long time or cannot be served, this might cause your web application to hang or stop.  Using True, the third parameter, you tell the XMLHttpRequest object to continue the execution after the request to the server has been sent.  And since we cannot simply start using the response from the server request before we are sure the request has been completed, we need to set the onreadystatechange property of the XMLHttpRequest, to a function (or name of a function) to be executed after completion.  In this onreadystatechange function we test the readyState property before we can use the result of the server call. So, lets make a slight modification to our above code.
    <head>
    <script type=”text/javascript”>
    function loadXMLDoc(url)
    {
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
    xmlhttp=new ActiveXObject(”Microsoft.XMLHTTP”);
    }
    xmlhttp.onreadystatechange=function()
    {
    if(xmlhttp.readyState==4)
    {document.getElementById(’suggestion’).innerHTML=xmlhttp.responseText}
    }
    xmlhttp.open(”GET”,url,true);
    xmlhttp.send(null);
    document.getElementById(’suggestion’).innerHTML=xmlhttp.responseText;
    }
    </script>
    </head>
    Another question, what this readyState is? Well, this property holds the status of the server’s response.
    State     Description
    0              The request is not initialized
    1              The request has been set up
    2              The request has been sent
    3              The request is in process
    4              The request is complete
    Now, enough theory. Let’s make a Google suggest kind of stuff and get an understanding, how AJAX works.
    AJAX with ASP.NET 4.0 (.NET 4.0 framework is still in beta but a lot to offer)
    We are going to use .NET 4.0 framework to show our demo of AJAX using VS.NET 2010 Express (Beta).  If you do not have VS.NET 2010 Express (Beta), you can download it fromhttp://msdn.microsoft.com/en-us/vstudio/dd582936.aspx. Remember .NET 4.0 has not been made public yet . Microsoft plans to make it public in March 2010. You can develop this demo in any serve side script you prefer.  Since I use .NET, ROR (Ruby on Rails) & PHP for my web development and since now I am playing a lot with new .NET 4.0, I planned to show the demo in VS.NET 2010 Express.  Before we start developing our Google suggest demo, I would like to make it clear that we can create AJAX based application in various way and that depends on the technology & IDE you are using. Though we will using VS.NET 2010 (Beta) for our demo, I have taken an approach which will work with all the serve side technologies with little alteration of syntaxes. Let’s design what we will be in need of:
    (1)    A request page – default.aspx
    (2)    A URL to call which will return the output – search.aspx
    (3)    VS.NET inbuilt Sql Server 2005 support to create database file in mdf – GSuggest.mdf
    (4)    A table in GSuggest.mdf – Suggestion
    (5)    A column in Suggestion table – SuggestionText (nchar(100)
    (6)    A LINQ to SQL file – SuggestionDB.dbml
    Our pseudo code :-
    (1)    Default.aspx  is our front page to communicate with web server using AJAX.
    (2)    onKeyUp Javascript event of search text box on Default.aspx, calls the search.aspx page via AJAX.
    (3)    Search.aspx page process the query using LINQ – SQL and returns back the output string. (Assuming only one output for our demo)
    (4)    Default.aspx gets the signal from search.aspx and shows the output as we type in the characters.
    Let us start building the our application.
    (1) Click      Start-> Microsoft Visual Web Developer Express 2010 – ENU
    pic1-1024x640
    (2) Click      File-> New Project
    Select “Visual C#” from Installed Templates and “ASP.NET Web Application” as application. Give you project a name (AjaxProject in our case) and choose a location to create a project.
    pic2-1024x640
    (3) Project will be created. Now right click  “App Data” folder -> Add  -> New Item
    pic3-1024x640
    (4) Select “Data” from installed templates and “Sql Server Database”. Give your database a name (GSuggest in our case).
    pic4-1024x640
    (5) Database created. Now go to “Database Explorer” and browse GSuggest.mdf database. Right click on it and choose “Add New Table”
    pic5-1024x640
    (6) Create a Column called “SuggestionText”  and data type as NCHAR(100).  Save this table as “Suggestion”.
    (7) Now right click on project -> Add -> New Item.

    pic71-1024x640
    (8) Select “Data” as installed templates and “LINQ to SQL class” from middle. Give your dbml file name as SuggestionDB.dbml

    pic8-1024x640
    (9) Drag and drop the Suggestion table from database explorer to SuggestionDB.dbml file
    pic9-1024x640
    (10)Add following code in your Default.aspx file.

    <%@ Page Title=”Home Page” Language=”C#” MasterPageFile=”~/Site.master” AutoEventWireup=”true”
    CodeBehind=”Default.aspx.cs” Inherits=”AjaxProject._Default” %>
    <asp:Content ID=”HeaderContent” runat=”server” ContentPlaceHolderID=”HeadContent”>
    </asp:Content>
    <asp:Content ID=”BodyContent” runat=”server” ContentPlaceHolderID=”MainContent”>
    <script type=”text/javascript”>
    var xmlhttp = null;
    function ShowSuggestions(str) {
    if (str.length == 0) {
    document.getElementById(”txtHint”).innerHTML = “”;
    return;
    }
    if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp = new XMLHttpRequest();
    }
    else {
    // code for IE6, IE5
    xmlhttp = new ActiveXObject(”Microsoft.XMLHTTP”);
    }
    var url = “Search.aspx?q=” + str;
    xmlhttp.open(”GET”, url, false);
    xmlhttp.send(null);
    document.getElementById(”txtHint”).innerHTML = xmlhttp.responseText;
    }
    </script>
    <h2>
    Welcome to ASP.NET AJAX!
    </h2>
    <input type=”text” id=”txt1″ onkeyup=”ShowSuggestions(this.value)” />
    <p>Suggestions: <span id=”txtHint”></span></p>
    </asp:Content>
    Above code is very easy to understand. We are taking one input box and one txtHint span. Text box is supposed to take the input from user whereas txtHint span will render the suggestions. Please examine the input box carefully. We have used a javascript function ShowSuggestion which passes input text value id to the function. Now we already know, how to call the server using AJAX. We are taking Search.aspx page as a parameter in open method and one additional “q” parameter. Q is nothing but the parameter name for GET and we pass the input text value. As we type in this Javascript function will be called and it sends its request to search.aspx page with necessary parameter and renders the “Suggestion”.
    (11)Now let’s write some code is search.aspx code behind which is suppose feed us the output.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    namespace AjaxProject
    {
    public partial class Search : System.Web.UI.Page
    {
    private SuggestionDBDataContext db = new SuggestionDBDataContext();
    protected void Page_Load(object sender, EventArgs e)
    {
    var sugtext = db.Suggestions;
    string suggestion = (from sgText in sugtext
    where sgText.SuggestionText.StartsWith(Request.QueryString["q"])
    select sgText.SuggestionText).FirstOrDefault();
    if (string.IsNullOrEmpty(suggestion))
    Response.Write(”No Suggestion Found”);
    else
    Response.Write(suggestion);
    Response.End();
    }
    }
    }
    Let’s understand the code above. To access our table Suggestion we created a couple of minutes back, we need to connect to the database and call the Suggestion table and query if it has some data starts with the text entered in the input box (Default.aspx has sent its request). Well, Microsoft is doing enough for developers to reduce the development time. Have you realized that when we created out dbml file and dropped Suggestion table on it, it automatically creates the connection string and saved it into web.config file?  Yes, it has. So no need to explicitly define the database connection. We just have to instantiate the context created in dbml file. Since this not a tutorial on ASP.NET, so I will not explain context and other things. It may occupy a whole book if I need to write about it. You can always google around and find. The code will remain same for the developers who are working on VS.NET 2008 (.NET 3.5 framework) . Ok enough theory. Let’s understand our code we just wrote. Since we can write direct SQL code using LINQ to SQL, so we followed the same path. We just accessed the Suggestion table through sugtext and applied LIKE query (StartWith) with our input entered.
    (from sgText in sugtext
    where sgText.SuggestionText.StartsWith(Request.QueryString["q"])
    select sgText.SuggestionText).FirstOrDefault();
    Please study the above code very carefully. We just wrote a SQL query using LINQ to SQL and got our Suggestion.  Since we may or may not get the suggestion stored in the Suggestion table, so we are checking whether it is null or not.
    if (string.IsNullOrEmpty(suggestion))
    Response.Write(”No Suggestion Found”);
    else
    Response.Write(suggestion);
    Response.End();
    Finally we are returning back the output in our Default.aspx page using Response.Write. You may come across the below screens.
    Input matches
    pic10-1024x640
    Input does not matches
    pic11-1024x640
    Yes, so simple. In fact we can trace your javascript code in VS.NET 2010 to see the entire process. Just set the breakpoints and run your application.
    pic12-1024x640
    Microsoft has come up with UI ToolKit called AJAX toolkit. You can navigate this linkhttp://www.codeplex.com/AjaxControlToolkit and can play with it. Using AJAXToolkit you can create a world class web application with very rich user interface.
    Future of AJAX
    Well, AJAX future is very promising and a lot of web applications are around for which we can feel proud. Social networks web application, corporate intranet applications, interaction with Microsoft Virtual Earth to name a few. I am sure by this time you want to go back and get your hands dirty with AJAX. So what are you waiting for? Go and make rich UI web application withAJAX and learn its true power.
    asp.net cookie example: how to create a cookie


    1. <%@ Page Language="C#" %>  
    2. <%@ Import Namespace="System.Net" %>  
    3.   
    4. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
    5.   
    6. <script runat="server">  
    7.     protected void Page_Load(object sender, System.EventArgs e) {  
    8.         HttpCookie userCookie = new HttpCookie("UserInfo");  
    9.         userCookie["Country"] = "Italy";  
    10.         userCookie["City"] = "Rome";  
    11.         userCookie["Name"] = "Jones";  
    12.         userCookie.Expires = DateTime.Now.AddDays(3);  
    13.         Response.Cookies.Add(userCookie);  
    14.         Label1.Text = "Cookie create successful!<br><br/>";  
    15.           
    16.         HttpCookie cookie = Request.Cookies["UserInfo"];  
    17.           
    18.         if (cookie != null)   
    19.         {  
    20.             string country = cookie["Country"];  
    21.             string city = cookie["City"];  
    22.             string name = cookie["Name"];  
    23.             Label2.Text = "Cookie Found and read<br/>";  
    24.             Label2.Text += "Name: " + name;  
    25.             Label2.Text += "<br />Country: " + country;  
    26.             Label2.Text += "<br />City: " + city;  
    27.         }  
    28.     }  
    29. </script>  
    30.   
    31. <html xmlns="http://www.w3.org/1999/xhtml">  
    32. <head runat="server">  
    33.     <title>asp.net cookie example: how to create a cookie</title>  
    34. </head>  
    35. <body>  
    36.     <form id="form1" runat="server">  
    37.     <div>  
    38.         <h2 style="color:Teal">asp.net Cookie example: Create a cookie</h2>  
    39.         <asp:Label ID="Label1" runat="server" Font-Size="Large" ForeColor="SeaGreen">  
    40.         </asp:Label>  
    41.         <asp:Label ID="Label2" runat="server" Font-Size="Large" ForeColor="Crimson">  
    42.         </asp:Label>  
    43.     </div>  
    44.     </form>  
    45. </body>  
    46. </html>  


    QueryString Example In Asp.Net 2.0,3.5,4.0 With Multiple Variable Values Using C# And VB.NET. Several time in ASP.NET applications we need to transfer data or information provided by user from one aspx page to another.

    We can achieve this using several methods like Cookies,Session or Crosspage posting

    In this post i am explaining how to use querystrings.

    Example url with querystring can be something similar like this

    http://yourdomainname.com/defauld.aspx?variable1=value1&variable2=value2

    Suppose we have a textbox txtData and we want it's value on other page
    than in code behind we would write in click event of btnGo


    private void btnGO_Click(object sender, System.EventArgs e)
    {
    Response.Redirect("Default2.aspx?Value=" +
    txtData.Text);
    }
    

    Or

    private void btnGO_Click(object sender, System.EventArgs e)
    {
    Response.Redirect("Default2.aspx?city=" +
    txtData.Text + "&country=" + txtcountry.Text);
    }
    


    Now to retrieve these values on other page we need to use request.querystring, we can either retrieve them by variable name or by index

    private void Page_Load(object sender,System.EventArgs e)
    {
    txtCity.Text = Request.QueryString["city"];
    txtCountry.Text = Request.QueryString["country"];
    }

    Or we can also use

    private void Page_Load(object sender,System.EventArgs e)
    {
    txtCity.Text = Request.QueryString[0];
    txtCountry.Text = Request.QueryString[1];
    }



    QueryString can't be used for sending long data because it has a max lenght limit

    Data being transferred is visible in url of browser

    To use spaces and & in query string we need to replace space by %20 and & by %26


    private void btnGO_Click(object sender, System.EventArgs e)
    {
    Response.Redirect("Default2.aspx?Value=" +
    txtData.Text.Replace(" ","%20");
    }
    

    Or we can use Server.UrlEncode method

    private void btno_Click(object sender, System.EventArgs e)
    {
    Response.Redirect("Default2.Aspx?" +
    "Name=" + Server.UrlEncode(txtData.Text));
    }
    The RegularExpressionValidator is a bit more difficult to write about, because it requires knowledge of Regular Expressions to really use it. However, RegularExpressionValidator is one of the most useful validators, because it can be used to check the validity of any kind of string. If you don't feel like learning Regular Expressions, but still feel like using this validator, have a look around the Internet. You can find many pre-made expressions out there, which can be very useful to you. Here is an example where we require a 4 digit number - nothing else is acceptable:
    4 digit number:<br />
    <asp:TextBox runat="server" id="txtNumber" />
    <asp:RegularExpressionValidator runat="server" id="rexNumber" 
     controltovalidate="txtNumber" validationexpression="^[0-9]{4}$"
      errormessage="Please enter a 4 digit number!" />
    <br /><br />
    
    The only new attribute we use, is the validationexpression. This attribute simply holds the Regular Expression which should be used to validate the field. Since Regular Expressions are beyond the scope of this tutorial, I won't try to explain it, other than it simply tells the validator that a value of 4 digitgs is acceptable, and nothing else. You can use the RegularExpressionValidator for almost everything, for instance validating an e-mail or an URL.

    Try switching to Design view and select the RegularExpressionValidator on your page. Now have a look in the Properties tab of VWD. The ValidationExpression attribute has a button next to it, and if you click it, you will gain access to some default expressions, delivered by the ASP.NET team, for various purposes. Just select one of them, to use in your validator.