raghava asp.net

Upload: rava

Post on 30-May-2018

224 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/14/2019 RAghaVA ASP.Net

    1/24

    Building a Web Application

    What's New in 2.0

    Dynamically Compiled Classes - In addition to placing pre-compiled classes in the Bin directory,ASP.NET 2.0 now allows you to place shared class file sources in the App_Code directory, where

    they will be dynamically compiled just like ASPX pages.

    Simplified Code Behind Pages - Code-behind files in ASP.NET 2.0 use a new language feature

    called partial classes, which allow code-behind files to be dynamically compiled with their associatedASPX pages into a single class type. This means you no longer need to declare member variables inthe code-behind page for each control, which greatly simplifies maintenance of sites that use this

    code-separation technique.

    Several New Server Controls - ASP.NET 2.0 include over 50 new controls, making it easier thanever to create common UI elements in your web pages. For example, the Data controls simplify

    data access scenarios, the Login controls add security to your site, the Navigation controls enablesite navigation, and WebPart controls allow you to easily create personalized web pages.

    New Declarative Expression Syntax - The declarative expression syntax in ASP.NET 2.0 allowsyou to substitute application settings, connection strings, and localization resources into your pagesbefore they are parsed and executed.

    This section discusses these and other features of basic ASP.NET applications.

    A web application in ASP.NET is a collection of pages, controls, code modules, and services all running under

    a single web server application directory (usually IIS). ASP.NET makes it really easy to build the types ofdynamic web applications that exist everywhere on the Internet today. It provides a simple programming

    model based on the .NET Framework and several built-in controls and services that enable many of thecommon scenarios found in most applications, with very little effort or code. In this section we demonstrate

    the basic elements of a web application that we will use throughout the remainder of Quickstart tutorial,including:

    The ASP.NET Page Framework (Web Forms)

    Web and HTML Server Controls

    Shared Code Modules or Assemblies

    This section also discusses a few improvements made to these application building blocks in ASP.NET 2.0over previous versions of ASP.NET.

    Introduction to ASP.NET Pages

    The ASP.NET Web Forms page framework is a scalable common language runtime programming model thatcan be used on the server to dynamically generate Web pages. Intended as a logical evolution of ASP

    (ASP.NET provides syntax compatibility with existing pages), the ASP.NET page framework has beenspecifically designed to address a number of key deficiencies in the previous model. In particular, it providesthe ability to create and use reusable UI controls that can encapsulate common functionality and thusreduce the amount of code that a page developer has to write, the ability for developers to cleanly structuretheir page logic in an orderly fashion (not "spaghetti code"), and the ability for development tools to provide

    strong WYSIWYG design support for pages (existing classic ASP code is opaque to tools). This section of theQuickStart provides a high-level code walkthrough of some basic ASP.NET page features. Subsequentsections of the QuickStart drill down into more specific details.

    Writing Your First ASP.NET Page

    ASP.NET pages are text files with an .aspx file name extension. Pages consist of code and markup and aredynamically compiled and executed on the server to produce a rendering to the requesting client browser

    (or device). They can be deployed throughout an IIS virtual root directory tree. When a browser client

    requests .aspx resources, the ASP.NET runtime parses and compiles the target file into a .NET Frameworkclass. This class can then be used to dynamically process incoming requests. (Note that the .aspx file iscompiled only the first time it is accessed; the compiled type instance is then reused across multiple

    requests).

    An ASP.NET page can be created simply by taking an existing HTML file and changing its file name extensionto .aspx (no modification of code is required). For example, the following sample demonstrates a simple

    HTML page that collects a user's name and category preference and then performs a form postback to theoriginating page when a button is clicked:

    C# Intro1.aspx

    http://quickstarts.asp.net/QuickStartv20/util/srcview.aspx?path=~/aspnet/samples/pages/intro/intro1.srchttp://quickstarts.asp.net/QuickStartv20/aspnet/samples/pages/intro/intro1_cs.aspx
  • 8/14/2019 RAghaVA ASP.Net

    2/24

    Important: Note that nothing happens yet when you click the Lookup button. This is because the .aspx filecontains only static HTML (no dynamic content). Thus, the same HTML is sent back to the client on each trip

    to the page, which results in a loss of the contents of the form fields (the text box and drop-down list)between requests.

    Name:

    Category: psychology business popular_comp

    Adding Simple Code to a Page

    ASP.NET provides syntax compatibility with existing ASP pages. This includes support for code

    render blocks that can be intermixed with HTML content within an .aspx file. These code blocks execute in atop-down manner at page render time.

    The below example demonstrates how render blocks can be used to loop over an HTML block

    (increasing the font size each time):

    C# Intro2.aspx

    Important: Unlike with ASP, the code used within the above blocks is actually compiled--notinterpreted using a script engine. This results in improved runtime execution performance.

    Name:

    Category: psychology business popular_comp

    http://quickstarts.asp.net/QuickStartv20/util/srcview.aspx?path=~/aspnet/samples/pages/intro/intro2.srchttp://quickstarts.asp.net/QuickStartv20/aspnet/samples/pages/intro/intro2_cs.aspx
  • 8/14/2019 RAghaVA ASP.Net

    3/24

    Welcome to ASP.NET

    ASP.NET page developers can utilize code blocks to dynamically modify HTML output much as they

    can today with ASP. For example, the following sample demonstrates how code blocks can be usedto interpret results posted back from a client.

    C# Intro3.aspx

    Important: While code blocks provide a powerful way to custom manipulate the text outputreturned from an ASP.NET page, they do not provide a clean HTML programming model. As the sample

    above illustrates, developers using only code blocks must custom manage page state betweenround trips and custom interpret posted values.

    Name:

    Category:

  • 8/14/2019 RAghaVA ASP.Net

    4/24

    Introduction to ASP.NET Server Controls

    In addition to code and markup, ASP.NET pages can contain server controls, which are programmableserver-side objects that typically represent a UI element in the page, such as a textbox or image. Server

    controls participate in the execution of the page and produce their own markup rendering to the client. Theprinciple advantage of server controls is that they enable developers to get complex rendering andbehaviors from simple building-block components, dramatically reducing the amount of code it takes toproduce a dynamic Web page. Another advantage of server controls is that it is easy to customize their

    rendering or behavior. Server controls expose properties that can be set either declaratively (on the tag) orprogrammatically (in code). Server controls (and the page itself) also expose events that developers canhandle to perform specific actions during the page execution or in response to a client-side action that posts

    the page back to the server (a "postback"). Server controls also simplify the problem of retaining stateacross round-trips to the server, automatically retaining their values across successive postbacks.

    Server controls are declared within an .aspx file using custom tags or intrinsic HTML tags that contain a

    runat="server" attribute value. Intrinsic HTML tags are handled by one of the controls in the

    System.Web.UI.HtmlControls namespace. Any tag that doesn't explicitly map to one of the controls isassigned the type ofSystem.Web.UI.HtmlControls.HtmlGenericControl .

    The following sample uses four server controls: , ,

    , and . At run time these servercontrols automatically generate HTML content.

    C# Intro4.aspx

    Important: Note that these server controls automatically maintain any client-entered values between roundtrips to the server. This control state is not stored on the server (it is instead stored within an form field that is round-tripped between requests). Note also that no client-side script isrequired.

    Name:

    Category: psychology business popular_comp

    In addition to supporting standard HTML input controls, ASP.NET enables developers to utilize richer customcontrols on their pages. For example, the following sample demonstrates how the control

    can be used to dynamically display rotating ads on a page.

    http://quickstarts.asp.net/QuickStartv20/util/srcview.aspx?path=~/aspnet/samples/pages/intro/intro4.srchttp://quickstarts.asp.net/QuickStartv20/aspnet/samples/pages/intro/intro4_cs.aspx
  • 8/14/2019 RAghaVA ASP.Net

    5/24

    C# Intro5.aspx

    Important: A detailed listing of all built-in server controls can be found in the Control Reference section of

    this QuickStart.

    Name:

    Category: psychology business popular_comp

    Ads.xml:

    images/banner1.gif http://www.microsoft.com Alt Text Computers 80

    images/banner2.gif http://www.microsoft.com Alt Text

    Computers 80

    images/banner3.gif http://www.microsoft.com Alt Text Computers 80

    http://quickstarts.asp.net/QuickStartv20/aspnet/doc/ctrlref/standard/default.aspxhttp://quickstarts.asp.net/QuickStartv20/util/srcview.aspx?path=~/aspnet/samples/pages/intro/intro5.srchttp://quickstarts.asp.net/QuickStartv20/aspnet/samples/pages/intro/intro5_cs.aspxhttp://quickstarts.asp.net/QuickStartv20/aspnet/doc/ctrlref/standard/default.aspx
  • 8/14/2019 RAghaVA ASP.Net

    6/24

    Handling Server Control Events

    Each ASP.NET server control is capable of exposing an object model containing properties, methods, and

    events. ASP.NET developers can use this object model to cleanly modify and interact with the page.

    The following example demonstrates how an ASP.NET page developer can handle the OnClick event fromthe control to manipulate the Text property of the control.

    C# Intro6.aspx

    This simple sample is functionally equivalent to the "Intro3" sample demonstrated earlier in this section.

    Note, however, how much cleaner and easier the code is in this new server-control-based version. As we willsee later in the tutorial, the ASP.NET page Framework also exposes a variety of page-level events that youcan handle to write code to execute a specific time during the processing of the page. Examples of theseevents are Page_Load and Page_Render.

    void SubmitBtn_Click(Object sender, EventArgs e) {Message.Text = "Hi " + HttpUtility.HtmlEncode(Name.Text) + ", you

    selected: " + Category.SelectedItem;}

    Name:

    Category: psychology

    business popular_comp

    http://quickstarts.asp.net/QuickStartv20/util/srcview.aspx?path=~/aspnet/samples/pages/intro/intro6.srchttp://quickstarts.asp.net/QuickStartv20/aspnet/samples/pages/intro/intro6_cs.aspx
  • 8/14/2019 RAghaVA ASP.Net

    7/24

    Ads.xml:

    images/banner1.gif

    http://www.microsoft.com Alt Text Computers 80

    images/banner2.gif http://www.microsoft.com Alt Text Computers 80

    images/banner3.gif http://www.microsoft.com Alt Text Computers 80

    Working with Server Controls

    ASP.NET server controls are identified within a page using declarative tags that contain a runat="server"attribute. The following example declares three server controls andcustomizes the text and style properties of each one individually.

    C# Controls1.aspx

    Declaring Server Controls

    This sample demonstrates how to declare the servercontrol and

    manipulate its properties within a page.

    This is Message One


    This is Message Two


    This is Message Three

    http://quickstarts.asp.net/QuickStartv20/util/srcview.aspx?path=~/aspnet/samples/pages/controls/controls1.srchttp://quickstarts.asp.net/QuickStartv20/aspnet/samples/pages/controls/controls1_cs.aspx
  • 8/14/2019 RAghaVA ASP.Net

    8/24

    Manipulating Server Controls

    You can programmatically identify an individual ASP.NET server control within a page by providing it with an

    id attribute. You can use this id reference to programmatically manipulate the server control's object modelat run time. For example, the following sample demonstrates how a page developer could programmatically

    set an control's Text property within the Page_Load event.

    C# Controls2.aspx

    void Page_Load(Object Src, EventArgs E) {Message.Text = "You last accessed this page at: " + DateTime.Now;

    }

    Manipulating Server Controls

    This sample demonstrates how to manipulate the server control within

    the Page_Load event to output the current time.

    Handling Control Events

    ASP.NET server controls can optionally expose and raise server events, which can be handled by pagedevelopers. A page developer may accomplish this by declaratively wiring an event to a control (where theattribute name of an event wireup indicates the event name and the attribute value indicates the name of a

    method to call). For example, the following code example demonstrates how to wire an OnClick event to abutton control.

    C# Controls3.aspx

    void EnterBtn_Click(Object Src, EventArgs E) {Message.Text = "Hi " + Name.Text + ", welcome to ASP.NET!";

    }

    Handling Control Action Events

    This sample demonstrates how to access a servercontrol within the "Click"

    event of a , and use its content to modify the textof a .

    http://quickstarts.asp.net/QuickStartv20/util/srcview.aspx?path=~/aspnet/samples/pages/controls/controls3.srchttp://quickstarts.asp.net/QuickStartv20/aspnet/samples/pages/controls/controls3_cs.aspxhttp://quickstarts.asp.net/QuickStartv20/util/srcview.aspx?path=~/aspnet/samples/pages/controls/controls2.srchttp://quickstarts.asp.net/QuickStartv20/aspnet/samples/pages/controls/controls2_cs.aspx
  • 8/14/2019 RAghaVA ASP.Net

    9/24

    Please enter your name:

    Handling Multiple Control Events

    Event handlers provide a clean way for page developers to structure logic within an ASP.NET page. Forexample, the following sample demonstrates how to wire and handle four button events on a single page.

    C# Controls4.aspx

    void AddBtn_Click(Object Src, EventArgs E) {

    if (AvailableFonts.SelectedIndex != -1) {

    InstalledFonts.Items.Add(newListItem(AvailableFonts.SelectedItem.Value));

    AvailableFonts.Items.Remove(AvailableFonts.SelectedItem.Value);}

    }

    void AddAllBtn_Click(Object Src, EventArgs E) {

    while (AvailableFonts.Items.Count != 0) {

    InstalledFonts.Items.Add(newListItem(AvailableFonts.Items[0].Value));

    AvailableFonts.Items.Remove(AvailableFonts.Items[0].Value);}

    }

    void RemoveBtn_Click(Object Src, EventArgs E) {

    if (InstalledFonts.SelectedIndex != -1) {

    AvailableFonts.Items.Add(newListItem(InstalledFonts.SelectedItem.Value));

    InstalledFonts.Items.Remove(InstalledFonts.SelectedItem.Value);

    }}

    void RemoveAllBtn_Click(Object Src, EventArgs E) {

    while (InstalledFonts.Items.Count != 0) {

    AvailableFonts.Items.Add(newListItem(InstalledFonts.Items[0].Value));

    InstalledFonts.Items.Remove(InstalledFonts.Items[0].Value);}

    }

    http://quickstarts.asp.net/QuickStartv20/util/srcview.aspx?path=~/aspnet/samples/pages/controls/controls4.srchttp://quickstarts.asp.net/QuickStartv20/aspnet/samples/pages/controls/controls4_cs.aspx
  • 8/14/2019 RAghaVA ASP.Net

    10/24

    Handling Multiple Control ActionEvents

    This sample demonstrates how to handle multiple control action eventsraised from

    different controls.

    Available Fonts

    Installed Fonts

    Roman Arial Black Garamond Somona Symbol Times Helvetica Arial

  • 8/14/2019 RAghaVA ASP.Net

    11/24

    Performing Page Navigation (Scenario 1)

    Page navigation among multiple pages is a common scenario in virtually all Web applications. The following

    sample demonstrates how to use the control to navigate to another page(passing custom query string parameters along the way). The sample then demonstrates how to easily get

    access to these query string parameters from the target page.

    C# Controls5.aspx

    Control5_cs.aspx:

    void Page_Load(Object Src, EventArgs E) {

    Random randomGenerator = new Random(DateTime.Now.Millisecond);

    int randomNum = randomGenerator.Next(0, 3);

    switch(randomNum) {

    case 0:Name.Text = "Scott";

    break;

    case 1:Name.Text = "Fred";

    break;

    case 2:Name.Text = "Adam";

    break;}

    AnchorLink.NavigateUrl = "controls_navigationtarget_cs.aspx?name="+ System.Web.HttpUtility.UrlEncode(Name.Text);

    }

    Performing Page Navigation (Scenario1)

    This sample demonstrates how to generate a HTML Anchor tag that willcause the client to

    navigate to a new page when he/she clicks it within the browser.

    Hi please click this link!

    http://quickstarts.asp.net/QuickStartv20/util/srcview.aspx?path=~/aspnet/samples/pages/controls/controls5.srchttp://quickstarts.asp.net/QuickStartv20/aspnet/samples/pages/controls/controls5_cs.aspx
  • 8/14/2019 RAghaVA ASP.Net

    12/24

    Controls_NavigationTarget_cs.aspx:

    void Page_Load(Object Sender, EventArgs e) {

    if (!Page.IsPostBack) {NameLabel.Text = Server.HtmlEncode(Request.QueryString["Name"]);

    }}

    Handling Page Navigation

    This sample demonstrates how to receive a navigation request fromanother

    page, and extract the querystring argument within the Page_Load event.

    Hi !

    Performing Page Navigation (Scenario 2)

    Not all page navigation scenarios are initiated through hyperlinks on the client. Client-side page redirects ornavigations can also be initiated from the server by an ASP.NET page developer by calling the

    Response.Redirect(url) method. This is typically done when server-side validation is required on someclient input before the navigation actually takes place.

    The following sample demonstrates how to use the Response.Redirect method to pass parameters toanother target page. It also demonstrates how to easily get access to these parameters from the targetpage.

    C# Controls6.aspx

    Control6_cs.aspx:

    void EnterBtn_Click(Object Src, EventArgs E) {

    // Navigate to a new page (passing name as a querystringargument) if // user has entered a valid name value in the

    if (Name.Text != "") {Response.Redirect("Controls_NavigationTarget_cs.aspx?name=" +

    System.Web.HttpUtility.UrlEncode(Name.Text));

    http://quickstarts.asp.net/QuickStartv20/util/srcview.aspx?path=~/aspnet/samples/pages/controls/controls6.srchttp://quickstarts.asp.net/QuickStartv20/aspnet/samples/pages/controls/controls6_cs.aspx
  • 8/14/2019 RAghaVA ASP.Net

    13/24

    } else {

    Message.Text = "Hey! Please enter your name in the textbox!";}

    }

    Performing Page Navigation (Scenario2)

    This sample demonstrates how to navigate to a new page from within a click event,

    passing a value as a querystring argument(validating first that the a legal

    textbox value has been specified).

    Please enter your name:

    Controls_Navigatin Target_cs.aspx:

    void Page_Load(Object Sender, EventArgs e) {

    if (!Page.IsPostBack) {NameLabel.Text = Server.HtmlEncode(Request.QueryString["Name"]);

    }}

    Handling Page Navigation

    This sample demonstrates how to receive a navigation request fromanother

    page, and extract the querystring argument within the Page_Load event.

  • 8/14/2019 RAghaVA ASP.Net

    14/24

    Hi !

    Code Behind vs. Code Inline

    ASP.NET provides two ways that you can organize code within your pages.

    Inline Code Separation

    The example below demonstrates a simple ASP.NET page with three server controls, a TextBox, Button, anda Label. Initially these controls just render their HTML form equivalents. However, when a value is typed in

    the TextBox and the Button is clicked on the client, the page posts back to the server and the page handlesthis click event in the code of the page, dynamically updating the Text property of the Label control. Thepage then re-renders to reflect the updated text. This simple example demonstrates the basic mechanicsbehind the server control model that has made ASP.NET one of the easiest Web programming models to

    learn and master.

    C# Inline Code Separation

    Note that in the preceding example the event handler for the Button was located between tags in the same page containing the server controls. ASP.NET calls this type ofpage programming code-inline, and it is very useful when you want to maintain your code andpresentation logic in a single file. However, ASP.NET also supports another way to factor your code and

    presentation content, called the code-behind model. When using code-behind, the code for handling eventsis located in a physically separate file from the page that contains server controls and markup. This cleardelineation between code and content is useful when you need to maintain these separately, such as whenmore than one person is involved in creating the application. It is often common in group projects to have

    designers working on the UI portions of an application while developers work on the behavior or code. Thecode-behind model is well-suited to that environment.

    void Button1_Click(object sender, EventArgs e){Label1.Text = "Hello " + TextBox1.Text;

    }

    ASP.NET Inline Pages

    Welcome to ASP.NET 2.0! Enter Your Name:

    Simplified Code Behind Model New in 2.0

    http://quickstarts.asp.net/QuickStartv20/util/srcview.aspx?path=~/aspnet/samples/simple/Inline.srchttp://quickstarts.asp.net/QuickStartv20/aspnet/samples/simple/Inline_cs.aspx
  • 8/14/2019 RAghaVA ASP.Net

    15/24

    ASP.NET 2.0 introduces an improved runtime for code-behind pages that simplifies the connections betweenthe page and code. In this new code-behind model, the page is declared as a partial class, which enables

    both the page and code files to be compiled into a single class at runtime. The page code refers to the code-behind file in the CodeFile attribute of the directive, specifying the class name in theInherits attribute. Note that members of the code behind class must be either public or protected (theycannot be private).

    C# CodeBehind Code Separation

    The advantage of the simplified code-behind model over previous versions is that you do not need to

    maintain separate declarations of server control variables in the code-behind class. Using partial classes(new in 2.0) allows the server control IDs of the ASPX page to be accessed directly in the code-behind file.This greatly simplifies the maintenance of code-behind pages.

    CodeBehing_cs.aspx:

    ASP.NET CodeBehind Pages Welcome to ASP.NET 2.0! Enter Your Name:

    CodeBehing_cs.aspx.cs:

    using System;

    public partial class CodeBehind_cs_aspx : System.Web.UI.Page{ protectedvoid Button1_Click(object sender, EventArgs e)

    {

    Label1.Text = "Hello " + TextBox1.Text;}

    }

    Sharing Code Between Pages

    Although you can place code inside each page within your site (using the inline or code-behind separationmodels described in the previous section), there are times when you will want to share code across severalpages in your site. It would be inefficient and difficult to maintain this code by copying it to every page thatneeds it. Fortunately, ASP.NET provides several convenient ways to make code accessible to all pages in an

    application.

    The Code Directory

    New in 2.0

    Just as pages can be compiled dynamically at runtime, so can arbitrary code files (for example .cs or .vbfiles). ASP.NET 2.0 introduces the App_Code directory, which can contain standalone files that containcode to be shared across several pages in your application. Unlike ASP.NET 1.x, which required these files tobe precompiled to the Bin directory, any code files in the App_Code directory will be dynamically compiled at

    runtime and made available to the application. It is possible to place files of more than one language underthe App_Code directory, provided they are partitioned in subdirectories (registered with a particular

    language in Web.config). The example below demonstrates using the App_Code directory to contain a singleclass file called from the page.

    http://quickstarts.asp.net/QuickStartv20/util/srcview.aspx?path=~/aspnet/samples/simple/CodeBehind.srchttp://quickstarts.asp.net/QuickStartv20/aspnet/samples/simple/CodeBehind_cs.aspx
  • 8/14/2019 RAghaVA ASP.Net

    16/24

    C# App_Code Folder Example

    CustomClass.cs:

    using System;

    publicclass CustomClass{ public String GetMessage(String input) { return "Hello " + input;

    }}

    CodeFolder_cs.aspx:

    void Button1_Click(object sender, EventArgs e){CustomClass c = new CustomClass();Label1.Text = c.GetMessage(TextBox1.Text);

    }

    ASP.NET Inline Pages

    Welcome to ASP.NET 2.0! Enter Your Name:

    By default, the App_Code directory can only contain files of the same language. However, you may partitionthe App_Code directory into subdirectories (each containing files of the same language) in order to containmultiple languages under the App_Code directory. To do this, you need to register each subdirectory in theWeb.config file for the application.

    The following example demonstrates an App_Code directory partitioned to contain files in both the VB andC# languages.

    C# Partitioned App_Code Folder Example

    CustomClass.cs:

    using System;

    publicclass CustomClass{ public String GetMessage(String input) {

    http://quickstarts.asp.net/QuickStartv20/util/srcview.aspx?path=~/aspnet/samples/simple/CodeFolder2.srchttp://quickstarts.asp.net/QuickStartv20/aspnet/samples/simple/CodeFolder_cs/CodeFolder2_cs.aspxhttp://quickstarts.asp.net/QuickStartv20/util/srcview.aspx?path=~/aspnet/samples/simple/CodeFolder.srchttp://quickstarts.asp.net/QuickStartv20/aspnet/samples/simple/CodeFolder_cs/CodeFolder_cs.aspx
  • 8/14/2019 RAghaVA ASP.Net

    17/24

    return "Hello " + input;}

    }

    CodeFolder2_cs.aspx:

    void Button1_Click(object sender, EventArgs e){CustomClass c = new CustomClass();Label1.Text = c.GetMessage(TextBox1.Text);

    CustomClass2 c2 = new CustomClass2();Label2.Text = c2.GetMessage(TextBox1.Text);

    }

    ASP.NET Inline Pages Welcome to ASP.NET 2.0! Enter Your Name:

    Web.config:

    The Bin Directory

    Supported in ASP.NET version 1, the Bin directory is like the Code directory, except it can containprecompiled assemblies. This is useful when you need to use code that is possibly written by someone otherthan yourself, where you don't have access to the source code (VB or C# file) but you have a compiled DLLinstead. Simply place the assembly in the Bin directory to make it available to your site. By default, all

    assemblies in the Bin directory are automatically loaded in the app and made accessible to pages. You mayneed to Import specific namespaces from assemblies in the Bin directory using the @Import directive at thetop of the page.

    The Global Assembly Cache

    The .NET Framework 2.0 includes a number of assemblies that represent the various parts of the

    Framework. These assemblies are stored in the global assembly cache, which is a versioned repository ofassemblies made available to all applications on the machine (not just a specific application, as is the casewith Bin and App_Code). Several assemblies in the Framework are automatically made available to ASP.NETapplications. You can register additional assemblies by registration in a Web.config file in your application.

  • 8/14/2019 RAghaVA ASP.Net

    18/24

    Note that you still need to use an @Import directive to make the namespaces in these assemblies availableto individual pages.

    Web Forms Syntax Reference

    An ASP.NET Web Forms page is a declarative text file with an .aspx file name extension. In addition to staticcontent, you can use eight distinct syntax markup elements. This section of the QuickStart reviews each ofthese syntax elements and provides examples demonstrating their use.

    Rendering Code Syntax: and

    Code rendering blocks are denoted with elements, allow you to custom-control content emission,and execute during the render phase of Web Forms page execution. The following example demonstrates

    how you can use them to loop over HTML content.

    C# VB

    Hello World!

    C# Reference1.aspx

    Code enclosed by is just executed, while expressions that include an equal sign, ,are evaluated and the result is emitted as content. Therefore renders the samething as the C# code .

    Note: For languages that use marks to end or separate statements (for example, the semicolon (;) in C#),it is important to place those marks correctly depending on how your code should be rendered.

    C# code

    A semicolon is necessary to end the statement.

    Wrong: Would result in "Response.Write("HelloWorld";);".

    A semicolon is not necessary.

    Reference1_cs.aspx:

    Hello World!

    Declaration Code Syntax:

    http://quickstarts.asp.net/QuickStartv20/util/srcview.aspx?path=~/aspnet/samples/pages/reference/reference1.srchttp://quickstarts.asp.net/QuickStartv20/aspnet/samples/pages/reference/reference1_cs.aspx
  • 8/14/2019 RAghaVA ASP.Net

    19/24

    Code declaration blocks define member variables and methods that will be compiled into the generatedPage class. These blocks can be used to author page and navigation logic. The following exampledemonstrates how a Subtract method can be declared within a block, and theninvoked from the page.

    C# VB

    int subtract(int num1, int num2) {return num1 - num2;

    }

    C# Reference2.aspx

    Important: Unlike ASP -- where functions could be declared within blocks -- all functions andglobal page variables must be declared in a tag. Functions declared within blocks will now generate a syntax compile error.

    Reference2_cs.aspx:

    int subtract(int num1, int num2) { return num1-num2;

    }

    0) {

    Response.Write("Value: " + number + "
    ");number = subtract(number, 1);

    } %>

    Server Control Syntax

    Custom ASP.NET server controls enable page developers to dynamically generate HTML user interface (UI)

    and respond to client requests. They are represented within a file using a declarative, tag-based syntax.These tags are distinguished from other tags because they contain a "runat=server" attribute. Thefollowing example demonstrates how an server control can be used withinan ASP.NET page. This control corresponds to the Label class in the System.Web.UI.WebControlsnamespace, which is included by default.

    By adding a tag with the ID "Message", an instance ofLabel is created at run time:

    The control can then be accessed using the same name. The following line sets the Text property of thecontrol.

    C# VB

    http://quickstarts.asp.net/QuickStartv20/util/srcview.aspx?path=~/aspnet/samples/pages/reference/reference2.srchttp://quickstarts.asp.net/QuickStartv20/aspnet/samples/pages/reference/reference2_cs.aspx
  • 8/14/2019 RAghaVA ASP.Net

    20/24

    Message.Text = "Welcome to ASP.NET";

    C# Reference3.aspx

    Reference3_cs.aspx:

    void Page_Load(Object sender, EventArgs e) {Message.Text = "Welcome to ASP.NET";

    }

    HTML Server Control Syntax

    HTML server controls enable page developers to programmatically manipulate HTML elements within a page.An HTML server control tag is distinguished from client HTML elements by means of a "runat=server"attribute. The following example demonstrates how an HTML server control can beused within an ASP.NET page.

    As with other server controls, the methods and properties are accessible programmatically, as shown in thefollowing example.

    C# VB

    void Page_Load(Object sender, EventArgs e) {Message.InnerHtml = "Welcome to ASP.NET";

    }

    ...

    C# Reference4.aspx

    Reference4_cs.aspx:

    void Page_Load(Object sender, EventArgs e) {Message.InnerHtml = "Welcome to ASP.NET";

    }

    Data Binding Syntax:

    http://quickstarts.asp.net/QuickStartv20/util/srcview.aspx?path=~/aspnet/samples/pages/reference/reference4.srchttp://quickstarts.asp.net/QuickStartv20/aspnet/samples/pages/reference/reference4_cs.aspxhttp://quickstarts.asp.net/QuickStartv20/util/srcview.aspx?path=~/aspnet/samples/pages/reference/reference3.srchttp://quickstarts.asp.net/QuickStartv20/aspnet/samples/pages/reference/reference3_cs.aspx
  • 8/14/2019 RAghaVA ASP.Net

    21/24

    The data binding support built into ASP.NET enables page developers to hierarchically bind control propertiesto data container values. Code located within a code block is only executed when the DataBindmethod of its parent control container is invoked. The following example demonstrates how to use the databinding syntax within an control.

    Within the datalist, the template for one item is specified. The content of the item template is specified usinga data binding expression and the Container.DataItem refers to the data source used by the datalist

    MyList.

    Here is a value:

    In this case the data source of the MyList control is set programmatically, and then DataBind() iscalled.

    C# VB

    void Page_Load(Object sender, EventArgs e) {ArrayList items = new ArrayList();

    items.Add("One");items.Add("Two");items.Add("Three");

    MyList.DataSource = items;MyList.DataBind();

    }

    Calling the DataBind method of a control causes a recursive tree walk from that control on down in thetree; the DataBinding event is raised on each server control in that hierarchy, and data bindingexpressions on the control are evaluated accordingly. So, if the DataBind method of the page is called, then

    every data binding expression within the page will be called.

    C# Reference5.aspx

    ASP.NET 2.0 also includes a new simplified databinding syntax, that allows controls to automatically data-

    bind to data source controls, without requiring you to call DataBind() in page code. This syntax is discussedin the section on Performing Data Access.

    Reference5_cs.aspx:

    void Page_Load(Object sender, EventArgs e) {

    ArrayList items = new ArrayList();

    items.Add("One");items.Add("Two");items.Add("Three");

    MyList.DataSource = items;

    MyList.DataBind();}

    Here is a value:

    http://quickstarts.asp.net/QuickStartv20/aspnet/doc/data/default.aspxhttp://quickstarts.asp.net/QuickStartv20/util/srcview.aspx?path=~/aspnet/samples/pages/reference/reference5.srchttp://quickstarts.asp.net/QuickStartv20/aspnet/samples/pages/reference/reference5_cs.aspxhttp://quickstarts.asp.net/QuickStartv20/aspnet/doc/data/default.aspx
  • 8/14/2019 RAghaVA ASP.Net

    22/24

    Object Tag Syntax:

    Object tags enable page developers to declare and create instances of variables using a declarative, tag-

    based syntax. The following example demonstrates how the object tag can be used to create an instance ofan ArrayList class.

    The object will be created automatically at run time and can then be accessed through the ID "items".

    C# VB

    void Page_Load(Object sender, EventArgs e) {

    items.Add("One");items.Add("Two");items.Add("Three");...

    }

    C# Reference6.aspx

    Reference6_cs.aspx:

    void Page_Load(Object sender, EventArgs e) {

    ArrayItems.Add("One");ArrayItems.Add("Two");ArrayItems.Add("Three");

    MyList.DataSource = ArrayItems;MyList.DataBind();

    }

    Here is a value:

    Server-Side Comment Syntax:

    Server-side comments enable page developers to prevent server code (including server controls) and static

    content from executing or rendering. The following sample demonstrates how to block content fromexecuting and being sent down to a client. Note that everything between is filtered out and

    only visible in the original server file, even though it contains other ASP.NET directives.

    http://quickstarts.asp.net/QuickStartv20/util/srcview.aspx?path=~/aspnet/samples/pages/reference/reference6.srchttp://quickstarts.asp.net/QuickStartv20/aspnet/samples/pages/reference/reference6_cs.aspx
  • 8/14/2019 RAghaVA ASP.Net

    23/24

    C# VB


    Main page content


    http://quickstarts.asp.net/QuickStartv20/util/srcview.aspx?path=~/aspnet/samples/pages/reference/reference8.srchttp://quickstarts.asp.net/QuickStartv20/aspnet/samples/pages/reference/reference8_cs.aspxhttp://quickstarts.asp.net/QuickStartv20/util/srcview.aspx?path=~/aspnet/samples/pages/reference/reference7.srchttp://quickstarts.asp.net/QuickStartv20/aspnet/samples/pages/reference/reference7_cs.aspx
  • 8/14/2019 RAghaVA ASP.Net

    24/24

    Expression Syntax: New in 2.0

    ASP.NET 2.0 adds a new declarative expression syntax for substituting values into a page before the page isparsed. This is useful for substituting connection string values or application settings defined in a Web.config

    file for server control property values. It can also be used to substitute values from a resource file forlocaization. More on connection string and resources expressions and expression handlers can be found inthe Performing Data Access,Internationalizing Your Application and Extending ASP.NET sections.

    http://quickstarts.asp.net/QuickStartv20/aspnet/doc/data/default.aspxhttp://quickstarts.asp.net/QuickStartv20/aspnet/doc/localization/default.aspxhttp://quickstarts.asp.net/QuickStartv20/aspnet/doc/localization/default.aspxhttp://quickstarts.asp.net/QuickStartv20/aspnet/doc/extensibility.aspxhttp://quickstarts.asp.net/QuickStartv20/aspnet/doc/data/default.aspxhttp://quickstarts.asp.net/QuickStartv20/aspnet/doc/localization/default.aspxhttp://quickstarts.asp.net/QuickStartv20/aspnet/doc/extensibility.aspx