ASP.net Web Application Web Forms
March 24, 2017 | Author: Manoj Manu | Category: N/A
Short Description
Download ASP.net Web Application Web Forms...
Description
ASP.NET – Web Forms Code Framework Development
Rakesh Singh NARESH I TECHNOLOGIES Hyderabad 0
ASP.NET Web Application Development Using Web Forms Code Framework in Visual Studio IDE: Using Visual Studio, you can create ASP.NET Web Forms. The Visual Studio Integrated Development Environment (IDE) lets you drag and drop server controls to lay out your Web Forms page. You can then easily set properties, methods, and events for controls on the page or for the page itself. These properties, methods, and events are used to define the web page's behaviour, look and feel, and so on. To write server code to handle the logic for the page, you can use a .NET language like Visual Basic or C#. ASP.NET Web Forms are:
Based on Microsoft ASP.NET technology, in which code that runs on the server dynamically generates Web page output to the browser or client device.
Compatible with any browser or mobile device. An ASP.NET Web page automatically renders the correct browser-compliant HTML for features such as styles, layout, and so on.
Compatible with any language supported by the .NET common language runtime, such as Microsoft Visual Basic and Microsoft Visual C#.
Built on the Microsoft .NET Framework. This provides all the benefits of the framework, including a managed environment, type safety, and inheritance.
Flexible because you can add user-created and third party controls to them.
ASP.NET Web Forms offer:
Separation of HTML and other UI code from application logic.
A rich suite of server controls for common tasks, including data access.
Powerful data binding, with great tool support.
Support for client-side scripting that executes in the browser.
Support for a variety of other capabilities, including routing, security, performance, internationalization, testing, debugging, error handling and state management.
ASP.NET Web Forms Helps You Overcome Challenges Web application programming presents challenges that do not typically arise when programming traditional client-based applications. Among the challenges are:
Implementing a rich Web user interface - It can be difficult and tedious to design and implement a user interface using basic HTML facilities, especially if the page has a complex layout, a large amount of dynamic content, and full-featured user-interactive objects. Separation of client and server - In a Web application, the client (browser) and server are different programs often running on different computers (and even on different operating systems). Consequently, the two halves of the application share very little information; they can communicate, but typically exchange only small chunks of simple information. Stateless execution - When a Web server receives a request for a page, it finds the page, processes it, sends it to the browser, and then discards all page information. If the user requests the same page again, the server repeats the entire sequence, reprocessing the page from scratch. Put another way, a server has no memory of pages that it has processed—page are Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.
Page |1
stateless. Therefore, if an application needs to maintain information about a page, its stateless
nature can become a problem. Unknown client capabilities - In many cases, Web applications are accessible to many users using different browsers. Browsers have different capabilities, making it difficult to create an
application that will run equally well on all of them. Complications with data access - Reading from and writing to a data source in traditional
Web applications can be complicated and resource-intensive. Complications with scalability - In many cases Web applications designed with existing methods fail to meet scalability goals due to the lack of compatibility between the various components of the application. This is often a common failure point for applications under a heavy growth cycle.
Meeting these challenges for Web applications can require substantial time and effort. ASP.NET Web Forms and the ASP.NET framework address these challenges in the following ways:
Intuitive, consistent object model - The ASP.NET page framework presents an object model that enables you to think of your forms as a unit, not as separate client and server pieces. In this model, you can program the page in a more intuitive way than in traditional Web applications, including the ability to set properties for page elements and respond to events. In addition, ASP.NET server controls are an abstraction from the physical contents of an HTML page and from the direct interaction between browser and server. In general, you can use server controls the way you might work with controls in a client application and not have to think about how to create the HTML to present and process the controls and their contents. Event-driven programming model - ASP.NET Web Forms bring to Web applications the familiar model of writing event handlers for events that occur on either the client or server. The ASP.NET page framework abstracts this model in such a way that the underlying mechanism of capturing an event on the client, transmitting it to the server, and calling the appropriate method is all automatic and invisible to you. The result is a clear, easily written code structure that supports event-driven development. Intuitive state management - The ASP.NET page framework automatically handles the task of maintaining the state of your page and its controls, and it provides you with explicit ways to maintain the state of application-specific information. This is accomplished without heavy use of server resources and can be implemented with or without sending cookies to the browser. Browser-independent applications - The ASP.NET page framework enables you to create all application logic on the server, eliminating the need to explicitly code for differences in browsers. However, it still enables you to take advantage of browser-specific features by writing client-side code to provide improved performance and a richer client experience. .NET Framework common language runtime support - The ASP.NET page framework is built on the .NET Framework, so the entire framework is available to any ASP.NET application. Your applications can be written in any language that is compatible that is with the runtime. In addition, data access is simplified using the data access infrastructure provided by the .NET Framework, including ADO.NET. Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.
Page |2
.NET Framework scalable server performance - The ASP.NET page framework enables you to scale your Web application from one computer with a single processor to a multi-computer Web farm cleanly and without complicated changes to the application's logic.
Deciding When to Create a Web Forms Application: You must consider carefully whether to implement a Web application by using either the ASP.NET Web Forms model or another model, such as the ASP.NET MVC framework. The MVC framework does not replace the Web Forms model; you can use either framework for Web applications. Before you decide to use the Web Forms model or the MVC framework for a specific Web site, evaluate the advantages of each approach.
Advantages of a Web Forms-Based Web Application: The Web Forms-based framework offers the following advantages:
It supports an event model that preserves state over HTTP, which benefits line-of-business Web application development. The Web Forms-based application provides dozens of events that are supported in hundreds of server controls.
It uses a Page Controller pattern that adds functionality to individual pages.
It uses view state or server-based forms, which can make managing state information easier.
It works well for small teams of Web developers and designers who want to take advantage of the large number of components available for rapid application development.
In general, it is less complex for application development, because the components (the Page class, controls, and so on) are tightly integrated and usually require less code than the MVC model.
Advantages of an MVC-Based Web Application:
The ASP.NET MVC framework offers the following advantages:
It makes it easier to manage complexity by dividing an application into the model, the view, and the controller.
It does not use view state or server-based forms. This makes the MVC framework ideal for developers who want full control over the behaviour of an application.
It uses a Front Controller pattern that processes Web application requests through a single controller. This enables you to design an application that supports a rich routing infrastructure.
It provides better support for test-driven development (TDD).
It works well for Web applications that are supported by large teams of developers and Web designers who need a high degree of control over the application behaviour.
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. Page |3
Creating a first ASP.Net Sample Web Site with C# Using Plain Text Editor i.e. Notepad environment with following resources and setup this website in IIS or you can say that required to host a website on a given web server i.e. IIS.
For Example: D:\ - Physical Location on the Server Machine SampleWebSite – Website Folder Images - Folder Ads1.jpg
Image Used in Web Form
Web Form - UI Default.aspx Default.aspx.cs Web Form – Code File Use the notepad text editor to create a web form (UI) file i.e. Default.aspx & Code File i.e. Default.aspx.cs as following: Default.aspx: ASP.NET Web Site function validate() { var firstName = document.getElementById("TextBox1").value; var lastName = document.getElementById("TextBox2").value; var error = ""; if (firstName == "") error += "Please Enter First Name" + "\n"; Client – Side Script Code if (lastName == "") error += "Please Enter Last Name" + "\n"; if (error != "") { alert(error); return false; } } Welcome to ASP.NET Web Site
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. Page |4
Default.aspx.cs (Code File): using using using using using using
System; System.Collections.Generic; System.Linq; System.Web; System.Web.UI; System.Web.UI.WebControls;
public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { TextBox1.Focus(); }
}
Server – Side Script Code
protected void Button1_Click(object sender, EventArgs e) { string firstName = TextBox1.Text.Trim(); string lastName = TextBox2.Text.Trim(); string fullName = firstName + " " + lastName; Label3.Text="Your Name Is: " + fullName; }
Once The Website is ready with their resources as shown above, You required to Host or setup a website on a given web server i.e. IIS Hosting a Web Site to an IIS Web Server: These are following steps to host or setup a Website to an IIS Webserver: 1. Open IIS Manger 2. To setup a new website in IIS, expand Server (Machine Name) -> Sites -> Default Web Site Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. Page |5
3. Right-Click on Default Web Site and choose Add Application and enter the details as following:
Click OK to complete hosting or setup a new website to an IIS Webserver.
Once a Website is hosted on IIS Web Server, It can be accessed from the same machine or any other client machine in the same network by making request to Webserver using Browser Interface as following: 1. Open Any Web Browser 2. Type the following URL: From The Same Machine: http://localhost/SampleWebSite/Default.aspx OR http://MachineName/SampleWebSite/ Default.aspx From Any Other Client Machine in the Same Network: http://ServerMachineName/SampleWebSite/ Default.aspx Or http://IP Address/SampleWebSite/ Default.aspx
Output:
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. Page |6
Creating First ASP.NET Website with Visual C# Programming Language in Visual Studio IDE (Integrated Development Environment):In Order to create an ASP.NET Web Application follow these steps: Steps to Create ASP.Net Web Application:1. Open Visual Studio 2010/2012/2013 2. Click on Main Menu i.e. File->New->Web Site, It Opens Automatically "New Web Site Templates Window" 3. Select "ASP.Net Empty Web Site" from Templates Section 4. Select appropriate .Net Framework Version such as 4.5.1/4.5/4.0/3.5/3.0/2.0 from top of Window. 5. Select Language as "Visual C#" or "Visual Basic" 6. Select Location as "File System" or "HTTP" or "FTP", and Specify the Web Site Name with Specified path 7. Finally Click Ok Button. After Clicking Ok button, it creates automatically New Empty Web Site with following Contents (Items): 1. Web.config (Application’s Configuration File)
Types of Web Site Project Creation in Visual Studio IDE: Describes different methods Visual Studio can use to access files for Web site projects. Visual Studio can access the files of a Web site project directly in a computer's file system, through IIS on the local computer or a remote computer, or through FTP on a remote computer. The names of Web site project types identify the method used: file-system sites, local or remote IIS sites, and File Transfer Protocol (FTP)–deployed sites. OR It describes how files are stored on your Web site, using either file-system based Web sites or those that require Internet Information Services (IIS). You can use Visual Studio to create and work with ASP.NET Web sites (which are also known as Web applications) in a variety of configurations: 1. File-System Sites, 2. HTTP (Local IIS Sites) 3. FTP (File Transfer Protocol) Sites. Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. Page |7
File-System Web Site Projects: In a file-system Web site project, you can create and edit files in any folder, whether on your local computer or in a folder on another computer that you access over a network. You are not required to run IIS on your computer. Instead, you can test pages by using the Visual Studio Development Server. You can create a file-system Web site project and later create an IIS virtual directory that points to the folder containing your pages.
Web Servers in Visual Studio for ASP.NET Web Projects: When you develop web projects in Visual Studio, you need a web server to test or run them. Visual Studio lets you test with different web servers, including IIS Express, Internet Information Services (IIS), External Hosts, or Custom Web Servers. You can use any of these web servers with a file-based web application project. For a file-based web site project, you can use IIS Express. The following table provides summary guidance for choosing a web server in Visual Studio/Visual Web Developer. Web server
When to use
IIS Express
IIS Express is the default web server for web application projects in Visual Studio 2012 and Visual Studio 2013, and it is recommended for both web application projects and web site projects.
Local IIS
Use IIS when you want to test your web application using the server environment that is closest to what the live site will run under, and it is practical for you to install and work with IIS on your development computer. You can use IIS with web site projects, but not with web application projects.
External Host
You can specify the URL of an external host that you will use for testing.
Custom Web Server
Visual Studio 2013 adds support for specifying custom Web servers in your projects; this functionality enables developers to define the environment for testing their Web applications.
IIS Express is designed to emulate IIS, but minor differences between IIS Express and the full version of IIS may result in errors that occur only after you have deployed your website to a production version of IIS. If you use IIS Express, it is recommended that you test your application on a staging server that uses the target version of IIS before deploying it to a live site. By default, Visual Studio 2012 and Visual Studio 2013 use IIS Express.
Using IIS Express with Visual Studio: IIS Express includes many of the features of IIS 7 and IIS 8 web servers without requiring you to install and manage IIS on your computer. Because IIS Express is similar to IIS 7 and IIS 8, it lets you transition web sites to IIS more smoothly than using other Web servers. IIS Express offers the following features:
It supports and enables the same extensibility model and Web.config file settings as IIS 7 and IIS 8.
It does not require changes in your web application code.
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. Page |8
It can be installed side-by-side with the full version of IIS and other web servers. You can choose a different web server for each project.
In corporate environments, IIS Express offers the following features:
It does not require an administrator account in order to run or debug applications.
It does not serve requests to a browser on another computer, making its approval easier in corporate environments.
It can be installed on versions of Windows that do not support IIS 7 or IIS 8.
Note: Although IIS Express is derived from IIS and supports the core features of IIS, there are some differences between these servers.
Installing IIS Express: IIS Express is installed automatically when you install Visual Studio 2012 and Visual Studio 2013. If you want to install IIS Express in Visual Studio 2010 (SP1 is required), you can use the Microsoft Web Platform Installer.
To install IIS Express
1. In a browser, go to the installation page (http://www.microsoft.com/web/gallery/install.aspx?appid=IISExpress) of the Microsoft.com/web site. 2. Download the installer and then follow the steps to finish the installation.
Using the IIS Express System Tray Application IIS Express starts automatically when you run a project in Visual Studio, and it stops when you close the web site project or web application project in Visual Studio. When IIS Express is running, it displays an icon in the system tray, as shown in the following illustration.
The following table lists typical tasks for IIS Express and how to perform them. Task
Steps
Display a list of all sites that are running on IIS Express
Right-click the IIS Express icon in the system tray, and then click Show All Applications.
View a web site directory location, configuration path, and .NET Framework version
Select the web site in the IIS Express window. The information will appear beneath the list of web sites.
Stop IIS Express
Right-click the tray icon and select Exit.
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. Page |9
HTTP (Local IIS Sites): You test local IIS Web site projects using a copy of IIS that is installed on your computer. When you create a local IIS Web site project, the pages and folders for your site are stored in a folder under the default IIS folder for Web sites, which is located at [drive]:\Inetpub\wwwroot. Visual Studio also creates the appropriate IIS configuration so that the Web site is recognized by IIS as an application.
Note: To create a local IIS Web site project, you need to have administrative privileges on the computer. Alternatively, you can create an IIS virtual directory in Visual Studio. In that case, the pages and folders for your Web site can be in any folder to which users have access, and a virtual directory in your local copy of IIS must point to the file location.
Using IIS with Visual Studio: The production web server for Microsoft operating systems is IIS, which can include a web server, File Transfer Protocol (FTP) server, Simple Mail Transfer Protocol (SMTP) virtual email server, and other facilities. In order to run IIS, you must be working with one of the versions of Windows that is listed in the following table:
Windows Version
IIS version
Windows Server 2012 R2 Windows 8.1
IIS 8.5
Windows Server 2012 Windows 8
IIS 8.0
Windows Server 2008 R2 Windows 7 (Home Premium, Professional, Enterprise, and Ultimate editions)
IIS 7.5
Windows Server 2008 Windows Vista (Home Premium, Business, Enterprise, and Ultimate editions)
IIS 7.0
Windows Server 2003 Windows XP Professional x64
IIS 6.0
Windows XP Professional x32
IIS 5.1 Note: This version of IIS is not recommended; you should use IIS Express if possible.
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 10
Advantages of Using IIS as a Development Server with Visual Studio Working directly with IIS as your development web server lets you work in an environment closer to that of an IIS production web server. This can help you solve configuration problems before your project goes live. If you use IIS Express, the transition to an IIS production web server might require you to perform extra configuration tasks because of the different security contexts between test and production servers.
Disadvantages of Using IIS as a Development Web Server: Using IIS as a development server can require more setup and configuration tasks in order to work with Visual Studio than using IIS Express, including the following: Both IIS and ASP.NET must be enabled in Windows, and ASP.NET must be registered with Windows. (Registration is a separate step if you installed the .NET Framework first, and then enabled IIS. Using ASP.NET IIS Registration Tool (Aspnet_regiis.exe).) You must run Visual Studio as an administrator in order to work with IIS. In addition, it might be impractical for you to work with IIS if any of the following apply: Your corporate workplace policy does not allow server roles like IIS to be enabled on developer computers. Your corporate workplace policy does not allow developers to have administrator accounts on IIS. You are developing ASP.NET web pages while working with a Home Edition of Windows, which does not support IIS. You do not want to host a web server on your computer (for example, on your home network) for security reasons. Your web project uses a SQL Server Express LocalDB database. In this case you can use IIS Express.
Remote IIS Web Site Projects: A remote Web site project uses IIS that is on another computer that you can access over a local area network. The remote computer must have IIS installed and be configured with FrontPage Server Extensions from Microsoft. When you create a remote Web site project, the pages and folders for your site are stored under the default IIS folder on the remote computer. By default, this folder is located at [drive]:\Inetpub\wwwroot. When you test pages in the project, they are served using IIS on the remote computer.
FTP Web Site Projects Visual Studio allows you to open and edit Web sites that are available on an FTP server. This is a typical scenario if your Web site is located on a hosting site. You can connect from within Visual Studio to any FTP server on which you have Read/Write permissions. You can then create and edit Web pages on that server. If the FTP server is configured with ASP.NET and an IIS virtual root that points to the FTP directory, you can also run your pages from the server to test them.
Choosing a Web Site Project Type: The following table summarizes the types of Web site projects that you can create in Visual Studio, which you can use when deciding which type of Web site meets your needs.
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 11
Web Site Project Type
Summary
File-system Web site project
Use a file-system Web site project when you want to create Web pages on your local computer or on a shared drive and you do not have IIS installed. You can create a filesystem Web site and later create an IIS virtual directory that points to the folder containing your pages. Advantages The site can be accessed only from the local computer, which reduces security vulnerabilities. You do not need to have IIS installed on your computer. You do not need administrative rights to create or debug a local file-system Web site. If the computer is configured to allow remote desktop connections, multiple users can create and debug local file-system Web sites at the same time. Disadvantages You cannot test a file-system Web site with IIS features, such as HTTP-based authentication, application pooling, and ISAPI filters. There are also some differences between the way the Visual Studio Development Server works and the way IIS works. Therefore, you should test your project by running it with IIS before deploying it to production.
Local IIS Web site project
Use when you want to create Web pages on your local computer and you have IIS installed. Advantages The site can be accessed from other computers if IIS is configured to make it available to them. You can test with IIS features, such as HTTP-based authentication, application pooling, and ISAPI filters. You should test with IIS before you deploy to production anyway due to differences between the Visual Web Development Server and IIS. Therefore, testing in Visual Studio more accurately represents how the site will behave in production (except that security is likely to be different in test and production.) Disadvantages You must have administrative rights to create or debug an IIS Web site project. Only one user on the computer can debug an IIS Web site project at one time. By default, remote access is enabled for a local IIS Web site project.
Remote Web project
Use when you want to create a Web site by using IIS running on a remote computer. The remote computer must be configured with FrontPage Server Extensions. Advantages You can test the Web site project on the server where it will be deployed. Multiple developers can work with the same remote Web site project at the same time. Disadvantages Configuration for debugging a remote Web site project is complex.
IIS site
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 12
FTP Web project
site
Only one developer can debug the remote Web site project at one time. All other requests are suspended while the developer is stepping through code.
Use an FTP Web site project when your site already exists on a remote computer that has been configured as an FTP server. (For example, your Internet service provider (ISP) has provided space on a server.) Advantages You can test the FTP Web site project on the server where it will be deployed. Disadvantages You do not have local copies of the FTP Web site project files unless you copy them yourself. You cannot create an FTP Web site project — you can only open one. Typical file editing operations, such as opening and saving files, might be slow. Because you are editing a live site, it is easier than with other Web project types to introduce an error that users can see.
For Example: 1. Web Location: File System Physical Path: C:\Users\Rakesh\Documents\Visual Studio 2012\WebSites\WebSiteFileSystem1 2. Web Location: HTTP Virtual Path: http://localhost/WebSiteHttp Physical Path: C: /Inetpub/wwwroot/WebSiteHttp1 Once a web site is created by choosing "ASP.NET Empty Web Site" Template, It's created with following contents:Web.config: Application’s Configuration File By Default Web.config (Application’s Configuration File) containing configuration settings of an application as following: Web.config:
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 13
Creating a New Web Form: To create a new web form, Open solution explorer, right click application root, select Add -> Add New Item, it opens automatically new window i.e. “Add New Template”, in which select Language as "Visual C#" at the left side, and choose Template as "Web Form, and accept the default name i.e. "Default.aspx" or change it as per need, and then finally click Add Button. A Web Form will be created with following two files:Default.aspx -----> UI Default.aspx.cs ------> Code Note: By Default ASP.Net supports separation of UI and Code for any Web Form (.aspx page), it is called "Code-Behind Model". Default.aspx or we can say any of the Web Form by default created with following markup in the source view:Skeleton Code: Default.aspx.cs: using using using using using using
System; System.Collections.Generic; System.Linq; System.Web; System.Web.UI; System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } } Note: ASP.NET Web Form Class in Code File must inherit from the System.Web.UI.Page Class.
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 14
Visual Studio Templates for Web Projects: Visual Studio includes project templates to help you get started when you create a web project. You can create web application projects or web site projects. By considering the most appropriate project type before you begin, you can save time when you create, test, and deploy the web project.
Web Project Templates: From the File menu, you can select either New Project or New Web Site. The New Project dialog box provides a list of web application templates. Use the web application project template to create web applications that are compiled into an assembly and that provide rich options for deployment. The New Web Site dialog box provides a list of web site templates. Use the Web Site project template when you want to compile the source code dynamically.
Note: You can install additional products by using the NuGet package manager. In some cases, these products include additional templates for new projects. The lists in this topic show you only the templates that are included by default with Visual Studio 2012.
Web Application Templates: Web application templates help you create a web project that is compiled into an assembly for deployment. The following table lists templates that appear in the New Project dialog box under the Web category after you select a language (Visual Basic or Visual C#). Project Template
Information
ASP.NET Web Forms Application
Use this project template to create a web application that is based on ASP.NET Web Forms pages and that includes the following functionality. A master page. A cascading style sheet. Login security that uses the ASP.NET membership system. Ajax scripting that uses jQuery. Navigation that uses a menu control. By default, the ASP.NET Web Application project template includes the following: Folders to contain membership pages, client script files, and cascading style sheet files. A data folder (App_Data), which is granted permissions that allow ASP.NET to read and write to it at run time. A master page (the Site.master file). Web pages named Default.aspx, Contact.aspx, and About.aspx. These content pages are based on the default master. A global application class (Global.asax file). A Web.config file. A Packages.config file.
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 15
ASP.NET MVC 3 Web Application
Use this project template to create web applications that use a model-view-controller pattern, using the ASP.NET MVC 3 release. The MVC pattern helps separate the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements. In addition, this project template promotes test-driven development (TDD).
ASP.NET MVC 4 Web Application
Use this project template to create web applications that use a model-view-controller pattern, using the ASP.NET MVC 4 release.
ASP.NET Empty Web Application
This template creates an ASP.NET web application that includes a Web.config file, but no other files. Use this project template when you do not require the functionality built into the standard template.
ASP.NET Dynamic Data Entities Web Application
Use this project template to create a Dynamic Data web application that uses the ADO.NET Entity Framework. This type of Dynamic Data web application can target any relational database. Dynamic Data automatically generates a functional web application for viewing and editing data, based on the schema of the data.
ASP.NET AJAX Server Control
Use this project template to create a web server control for ASP.NET Web Forms pages that incorporates Ajax functionality. The control consists of server and client code that work together to produce rich client behaviour.
ASP.NET AJAX Server Control Extender
Use this project template to create an Ajax component that enhances the client capabilities of standard ASP.NET web server controls.
ASP.NET Server Control
Use this project template to create a custom ASP.NET web server control that can be used in ASP.NET Web Forms pages.
Web Site Templates: Web site templates help you create a web project that by default is compiled dynamically. The following table lists templates that appear in the New Web Site dialog box. Project Template
Information
ASP.NET Web Forms Site
Use this project template to create a website that includes the following functionality: A master page. A cascading style sheet. Login security that uses the ASP.NET membership system. Ajax scripting that uses jQuery. Navigation using a menu control. By default, the ASP.NET Web Site project template includes the following: Folders to contain membership pages, client script files, and cascading style sheet files. A data folder (App_Data), which is granted permissions that allow ASP.NET to read and write to it at run time.
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 16
A master page (.master file). Web pages named Default.aspx and About.aspx. In the project template, these pages are content pages that use default master page. A global application class (Global.asax file). A Web.config file.
ASP.NET Web Site (Razor v1)
Use this project template to create a website that uses ASP.NET Web Pages with the Razor syntax.
ASP.NET Web Site (Razor v2)
Use this project template to create a website that uses ASP.NET Web Pages version 2 with Razor syntax.
ASP.NET Empty Web Site
This template creates an ASP.NET website that includes a Web.config file but no other files. Use this project template when you do not require the functionality built into the standard.
ASP.NET Dynamic Data Entities Web Site
Use this project template to create a Dynamic Data website that uses the ADO.NET Entity Framework. This type of Dynamic Data web application can target any relational database. Dynamic Data automatically generates a functional web application for viewing and editing data, based on the schema of the data.
WCF Service
Use this project template to create a Windows Communication Foundation (WCF) service. You can extend the service so that a website, web application, Silverlight application, Ajax application, or other client can call it.
ASP.NET Reports Web Site
Use this project template to create an ASP.NET website that contains a report (.rdlc file), a default ASP.NET Web Forms page (.aspx file) that contains a ReportViewer control, and a Web.config file.
Web Application Projects versus Web Site Projects in Visual Studio: In Visual Studio you can create web application projects or web site projects. You create or open a web application project by choosing New Project or Open Project in the Visual Studio File menu. You create or open a web site project by choosing New Web Site or Open Web Site in the File menu. It’s best to choose the right type before you create a web project, because it can be time-consuming, difficult, and error-prone to convert from one type to the other.
Note: For new development, we recommend that you choose web application projects. This topic explains that web site projects have some advantages, but many developers who choose web site projects eventually find that the disadvantages outweigh any perceived advantages. In addition, as new ASP.NET features are developed, they won’t always be made available for web site projects. For example, the next Visual Studio release after Visual Studio 2012 will have new tooling for creating web projects, and this new tooling will work only with web application projects.
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 17
The following table summarizes the main differences:
Project file structure
Compilation
Web application projects
Web site projects
A Visual Studio project file (.csproj or .vbproj) stores information about the project, such as the list of files that are included in the project, and any project-to-project references.
There is no project file (.csproj or .vbproj). All the files in a folder structure are automatically included in the site.
You explicitly compile the source code on the computer that is used for development or source control.
By default, compilation of code files (excluding .aspx and .ascx files) produces a single assembly.
The source code is typically compiled dynamically (automatically) by ASP.NET on the server the first time a request is received after the site has been installed or updated. You can precompile the site (compile in advance on a development computer or on the server). By default, compilation produces multiple assemblies.
Namespaces
Explicit namespaces are added to pages, controls, and classes by default.
Explicit namespaces are not added to pages, controls, and classes by default, but you can add them manually.
Deployment
You copy the assembly to a server. The assembly is produced by compiling the application.
You copy the application source files to a computer that has IIS installed on it. If you precompile the site on a development computer, you copy the assemblies produced by compilation to the IIS server. Visual Studio provides tools that integrate with Web Deploy (the IIS web deployment tool) to automate many deployment tasks.
Visual Studio provides tools that integrate with Web Deploy (the IIS web deployment tool) to automate many deployment tasks.
Note: There is no difference in performance between a web site project and a web application project. The only significant exceptions are the ones that have already been noted, and as a practical matter they apply only to very large sites. The first request to the web site might require the site to be compiled, which can result in a delay. And if the web site is running on an IIS server that is short on memory, including the entire site in a single assembly might use more memory than would be required for multiple assemblies.
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 18
The ASP.NET Page Structure Options: ASP.NET provides two paths for structuring the code of our ASP.NET pages. The first path utilizes the code-inline model. This model should be familiar to classic ASP 2.0/3.0 developers because all the code is contained within a single .aspx page. The second path uses ASP.NET’s code-behind model, which allows for code separation of the page’s business logic from its presentation logic. In this model, the presentation logic for the page is stored in an .aspx page, whereas the business logic piece is stored in a separate class file: .aspx.vb or .aspx.cs. Using the code-behind model is considered the best practice because it provides a clean model in separation of pure UI elements from code that manipulates these elements. It is also seen as a better means in maintaining code.
Code Inline Model: Inline Code refers to the code that is written inside an ASP.NET Web Page that has an extension of .aspx. It allows the code to be written along with the HTML source code using a tag. Its major point is that since it's physically in the .aspx file it's deployed with the Web Form page whenever the Web Page is deployed. You can say, In-line code is code that is embedded directly within the ASP.NET page (.aspx page). To build an ASP.NET page inline instead of using the code-behind model, we simply select the page type from the Add New Item dialog and make sure that the “Place Code in Separate File” check box is not selected. You can get at this dialog by right clicking the project or the solution in the Solution Explorer and selecting Add -> Add New Item. From here (Add New Item dialog), we can see the check box, we need to unselect if we want to build our ASP.NET pages inline code model. The following table shows the inline options when selecting files from this dialog: Inline Coding File Options Web Form Master Page Web User Control Web Services
Created File Extension .aspx file .master file .ascx file .asmx file
Example: The following code represents a simple page that uses the inline coding model:
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 19
Default.aspx: protected void Page_Load(object sender, EventArgs e) { txtValue1.Focus(); } void Calc(string op) { lblStatus.Text = string.Empty; txtResult.Text = string.Empty; try { float value1 = float.Parse(txtValue1.Text.Trim()); float value2 = float.Parse(txtValue2.Text.Trim()); float result = 0; switch (op) { case "+": result = value1 + value2; break; case "-": result = value1 - value2; break; case "*": result = value1 * value2; break; case "/": if (value2 == 0) throw new DivideByZeroException("You can't divide by zero!!!"); result = value1 / value2; break; } txtResult.Text = result.ToString(); } catch (FormatException ex1) { lblStatus.Text = ex1.Message; } catch (OverflowException ex2) { lblStatus.Text = ex2.Message; } catch (DivideByZeroException ex3) { lblStatus.Text = ex3.Message; }
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 20
} protected void btnAdd_Click(object sender, EventArgs e) { Calc("+"); } protected void btnSub_Click(object sender, EventArgs e) { Calc("-"); } protected void btnMul_Click(object sender, EventArgs e) { Calc("*"); } protected void btnDiv_Click(object sender, EventArgs e) { Calc("/"); } function validate() { var value1 = document.getElementById("txtValue1").value; var value2 = document.getElementById("txtValue2").value; var error = ""; if (value1 == "") error += "Please Enter Value1" + "\n"; if (value2 == "") error += "Please Enter Value2" + "\n"; if (error != "") { alert(error); return false; } } Inline Code Model Example Enter Value1:
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 21
Enter Value2: Result: Note: We can see that all the business logic is encapsulated in between tags. The nice feature of the inline model is that the business logic and the presentation logic are contained within the same file. Some developers find that having everything in a single viewable instance makes working with the ASP.NET page easier. Another great thing is that Visual Studio 2005 onwards provides IntelliSense when working with the inline coding model. Before Visual Studio 2005, this capability did not exist. Visual Studio .NET 2002/2003 forced you to use the code-behind model and, even if you fixed it so your pages were using the inline model, you lost all IntelliSense capabilities.
Code-Behind Model: Code Behind refers to the code for an ASP.NET Web page that is written in a separate class file that can have the extension of .aspx.cs or .aspx.vb depending on the language used. Here the code is compiled into a separate class from which the .aspx file derives. You can write the code in a separate .cs or .vb code file for each .aspx page. One major point of Code Behind is that the code for all the Web pages is compiled into a DLL file that allows the web pages to be hosted free from any Inline Server Code. Code-behind Model refers to code for our ASP.NET page that is contained within a separate class file. This allows a clean separation of our UI from our Code. To create a new page in our ASP.NET solution that uses the code - behind model, to build a page that uses the code - behind model, we first select the page in the Add New Item dialog and make sure the Place Code in Separate File check box is selected. The following table shows the code-behind model options when selecting files from this dialog: Code-Behind File Options Web Form Master Page Web User Control Web Services
Created File Extension .aspx file .aspx.cs file or .aspx.vb file .master file .master.cs file or .master.vb file .ascx file .ascx.cs file or .ascx.vb file .asmx file .cs file or .vb file
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 22
The idea of using the code - behind model is to separate the business logic and presentation logic into separate files. Doing this makes working with your pages easier, especially if you are working in a team environment where visual designers work on the UI of the page and coders work on the business logic that sits behind the presentation pieces. Code Behind approach is a better way to develop and design the .aspx page having basic layout of a web page containing all the necessary controls required for the GUI of the web page. Then include the C# or VB code behind class file for handling the events of controls. This mechanism separates the web page from design layout from the coding part. Example: Code - Behind model Sample Example:
Default2.aspx: Source View: function validate(v) { if (v != "") { document.getElementById("lblError").innerHTML = ""; var value1 = document.getElementById("txtValue1").value; var value2 = document.getElementById("txtValue2").value; var error = ""; if (value1 == "") error += "Please Enter Value1" + ""; if (value2 == "") error += "Please Enter Value2" + ""; if (error != "") { document.getElementById("lblError").innerHTML = error; return false; } else { __doPostBack(event, ""); return true; } }
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 23
else { document.getElementById("lblError").innerHTML = "Please Select Any Option!!!"; return false; } } Code Behind Model Example Enter Value1: Enter Value2: Select Option: Result: Code File (Default2.aspx.cs): using using using using using using
System; System.Collections.Generic; System.Linq; System.Web; System.Web.UI; System.Web.UI.WebControls;
public partial class Default2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { txtValue1.Focus(); } protected void ddlCalc_SelectedIndexChanged(object sender, EventArgs e)
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 24
{ lblError.Text = string.Empty; txtResult.Text = string.Empty; try { float value1 = float.Parse(txtValue1.Text.Trim()); float value2 = float.Parse(txtValue2.Text.Trim()); float result = 0; switch (ddlCalc.SelectedItem.Value) { case "+": result = value1 + value2; break; case "-": result = value1 - value2; break; case "*": result = value1 * value2; break; case "/": if (value2 == 0) throw new DivideByZeroException("You can't divide by zero!!!"); result = value1 / value2; break; } txtResult.Text = result.ToString(); } catch (FormatException ex1) { lblError.Text = ex1.Message; } catch (OverflowException ex2) { lblError.Text = ex2.Message; } catch (DivideByZeroException ex3) { lblError.Text = ex3.Message; } } } Note: It is important to note that the more preferred method is the code-behind model rather than the inline model. This method employs the proper segmentation between presentation and business logic in many cases.
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 25
Difference between Inline code and Code-behind. Inline Code Code Behind The business logic is in blocks in the same The HTML and controls are in the .aspx file, and the .aspx file that contains the HTML and controls. business logic is in a separate .aspx.cs or .aspx.vb file. When the page is deployed, the source code is All project class files (without the .aspx file) are deployed along with the Web Forms page, since it compiled into a .dll file, which are deployed to the is physically in the .aspx file. Though, we are not server without any source code. When a request for able to see the code, only the results are rendered the page is received, then an instance of the project when the page runs. .dll file is created and executed. The .aspx file derives from the Page class. The code for the page is compiled into a separate class from which the .aspx file derives. When we write inline code we write code in the The code-behind approach also improved same page with Html code between scripting tags. productivity (at some level) since the designer and So Each time when there is a request for page it the developer can continue working simultaneously compiles the code each time then server the page on the same set of application. Like classic asp because inline code cannot create dll. It's also easier to build & test the UI and the business logic (DLL) - separately or combined. Code Behind separates user interface from actual programming. This means graphic designers would look for only design matters while programmers work their way. Each specialized person work in their irrespective area and doesn't disturb each other to perform optimized work.
Directives for ASP.NET Web Forms: Directives specify settings that are used by the page and user-control compilers when the compilers process ASP.NET Web Forms pages (.aspx files) and user control (.ascx) files. ASP.NET directives can simply be described as instructions and settings used to describe how ASP.NET web form pages (.aspx) or User control (.ascx) pages will be processed by the .NET Framework.
Directives are instructions, inserted at the top of an ASP.NET page, to control the behaviour of the asp.net pages. So it is type of mixed settings related to how a page should render and processed. Asp.Net web form page framework supports the following directives: Directive
Description
@ Page
Defines page-specific attributes used by the ASP.NET page parser and compiler and can be included only in .aspx files.
@ Master
Identifies a page as a master page and defines attributes used by the ASP.NET page parser and compiler and can be included only in .master files.
@ Control
Defines control-specific attributes used by the ASP.NET page parser and compiler and can be included only in .ascx files (user controls).
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 26
@ Register
Associates aliases with namespaces and classes, which allow user controls and custom server controls to be rendered when included in a requested page or user control.
@ Import
Imports a namespace into a page or user control explicitly.
@ PreviousPageType
Creates a strongly typed reference to the source page from the target of a crosspage posting.
@ Application
The Application directive is used to define application-specific attributes. It is typically the first line in the Global.asax file.
@ Assembly
Links an assembly to the current page or user control declaratively.
@ Implements
Indicates that a page or user control implements a specified .NET Framework interface declaratively.
@ Reference
Links a page, user control, or COM control to the current page or user control declaratively.
@ OutputCache
Controls the output caching policies of a page or user control declaratively.
@ MasterType
Defines the class or virtual path used to type the Master property of a page.
@ WebService
Defines XML Web service specific (.asmx file) attributes used by the ASP.NET parser and compiler.
We use these directives in our applications whether the page uses the code-behind model or the inline coding model. Basically, these directives are commands that the compiler uses when the page is compiled. Directives are simple to incorporate into your pages. A directive is written in the following format: 1. Page Directive: Basically Page Directives are commands. These commands are used by the compiler when the page is compiled. When you want to specify the attributes for an ASP.NET page then you need to use @Page Directive. As you know, an ASP.NET page is a very important part of ASP.NET, so this directive is commonly used in ASP.NET. Every ASP.NET Web Form generally begins with the @ Page directive. This defines page-specific attributes used by the ASP.NET page parser and compiler and can be included only in .aspx files. This directive can be used only in Web Forms pages. You can include only one @ Page directive per .aspx file. Further, you can define only one Language attribute per @ Page directive, because only one language can be used per page. Page Directives can be placed anywhere in .aspx file. But
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 27
standard practice is to include them at the top of the file. The Page directive is made of many attributes. There are following major attributes:
Attributes:
Language: It Specifies the language used when compiling all inline rendering ( and ) and code declaration blocks within the page. Values can represent any .NET Framework-supported language, including C# or VB. Only one language can be used and specified per page. AutoEventWireup: Indicates whether the page's events are auto wired. True if event auto wiring is enabled; otherwise, false. By default its value is 'True' that means event of page class will be bound automatically with event handlers but if it is 'false' then we need to bind event handler with page class event manually. CodeFile: It specifies the name of the compiled file that contains the class associated with the page. This attribute is not used if the page uses inline code model as it represents to only code behind model. Inherits: Defines a code-behind class for the page to inherit. This can be any class derived from the Page class. This attribute is used with the CodeFile attribute, which contains the path to the source file for the code-behind class. The Inherits attribute is case-sensitive when using C# as the page language, and case-insensitive when using Visual Basic as the page language. Title: It specifies a title for the page that is rendered within the HTML tags in the response. The title can also be accessed programmatically as a property of the page. MasterPageFile: Sets the path to the master page for the content page or nested master page. Supports relative and absolute paths. Theme: Specifies a valid theme identifier to use on the page. When the Theme attribute is set without using the StyleSheetTheme attribute, it overrides individual style settings on controls, enabling you to create a unified and consistent look on a page. StyleSheetTheme: Specifies a valid theme identifier to use on the page. When the StyleSheetTheme attribute is set, individual controls can override the stylistic settings contained in a theme. Thus a theme can provide an overall look for a site, while the settings contained in the StyleSheetTheme attribute enable you to customize particular settings on a page and its individual controls. EnableTheming: Indicates whether themes are used on the page. True if themes are used; otherwise, false. The default is true. EnableViewState: Specifies whether view state is maintained across page requests. This value is true if view state is maintained, or false if view state is not maintained. The default is true. EnableSessionState: Defines session-state requirements for the page. True if session state is enabled; ReadOnly if session state can be read but not changed; otherwise, false. The default is true. ErrorPage: Defines a target URL for redirection if an unhandled page exception occurs. ValidateRequest: Indicates whether request validation should occur. If true, request validation checks all input data against a hard-coded list of potentially dangerous values. If a match occurs, an HttpRequestValidationException exception is thrown. The default is true. This feature is enabled in the machine configuration file (Machine.config). You can disable it in your application configuration file (Web.config) or on the page by setting this attribute to false.
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 28
Syntax: For Example: 2. Master Page Directive: The @Master Directive is quite similar to the @Page Directive. The only difference is that the @master directive is for Master pages. You need to note that, while using the @Master Directive you define the template page's property. Then any content page can inherit all the properties defined in the Master Page. But there are some properties that are only available in a Master Page. It Defines master page–specific (.master file) attributes that are used by the ASP.NET page parser and compiler. Syntax: Example: %@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage1.master.cs" Inherits="MasterPage" % 3. Control Directive: Defines attributes that are specific to user controls (.ascx files) that are used by the ASP.NET page parser and compiler. The @ Control directive is used when we build an Asp.Net web user controls. The @Control directive helps us to define the properties to be inherited by the user control. These values are assigned to the user control as the page is parsed and compiled. This directive can be used only in user controls. User controls are defined in files with the .ascx extension. You can include only one @ Control directive per .ascx file. Further, you can define only one Language attribute per @ Control directive, because only one language can be used per control. Note: The @ Control directive has a number of attributes in common with other directives that apply to an entire source file, such as the @ Page directive (used in .aspx files for Web pages) and the @ Master directive (used in .master files for master pages). Syntax: Example:
4. Register Directive: The @ Register directive associates aliases with namespaces and class names for notation in custom server control syntax. When you create a web user control and you drag and drop a web user control onto your .aspx pages, the Visual Studio automatically creates a @ Register directive at the top of the page. This register the user control on the page so that the control can be accessed on the .aspx page by a specific name. The @ Register directive can be included in Web Forms (.aspx files), Web User Controls (.ascx files), and Master Pages (.master files). Attributes: Assembly The assembly in which the namespace associated with the TagPrefix attribute resides.
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 29
Note: The assembly name cannot include a file extension. Also note that if the assembly attribute is missing, the ASP.NET parser assumes that there is source code in the App_Code folder of the application. If you have source code for a control that you want to register on a page without having to compile it, place the source code in the App_Code folder. ASP.NET dynamically compiles source files in the App_Code folder at run time. Namespace: The namespace of the custom control that is being registered. Src: The location (relative or absolute) of the declarative ASP.NET Web User Controls file to associate with the TagPrefix and TagName pair. TagName: An arbitrary alias to associate with a class. This attribute is only used for user controls. TagPrefix: An arbitrary alias that provides a shorthand reference to the namespace of the markup being used in the file that contains the directive. Syntax: Example: 5. Import Directive: As you know you need to define namespaces in your .cs class file before using any type like class, interface, struct, enum. So the @Import Directive imports namespaces. This directive supports just a single attribute "Namespace" and this attribute takes a string value that specifies the namespace to be imported. One thing you need to note is that the @Import Directive cannot contain more than one attribute/value pair. But you can use multiple lines. The @Import directive allows you to specify any namespaces to the imported to the Asp.Net pages or user controls. By importing, all the classes and interfaces of the namespace are made available to the page or user control. Explicitly imports a namespace into an ASP.NET application file (such as a Web page, a user control, a master page, or a Global.asax file), making all classes and interfaces of the imported namespace available to the file. The imported namespace can be part of the .NET Framework class library or a user-defined namespace. The @ Import directive cannot have more than one namespace attribute. To import multiple namespaces, use multiple @ Import directives. A set of namespaces can be automatically imported into .aspx pages. The imported namespaces are defined in the machine-level Web.config file, within the section of the element. The following namespaces are automatically imported into all pages: System System.Collections System.Collections.Specialized System.Configuration System.Text System.Text.RegularExpressions System.Web System.Web.Caching System.Web.Profile
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 30
System.Web.Security System.Web.SessionState System.Web.UI System.Web.UI.HtmlControls System.Web.UI.WebControls System.Web.UI.WebControls.WebParts
Example: 6. PreviousPageType Directive: This directive specifies the page from which any cross-page posting originates. The @PreviousPageType is a new directive makes excellence in asp.net 2.0 pages. The concept of cross-page posting between Asp.Net pages is achieved by this directive. This directive is used to specify the page from which the cross-page posting initiates. Attributes: TypeName: Specifies the type name for the previous page. VirtualPath: Specifies the path to the file that generates the strong type.
Note:
Use the @ PreviousPageType directive to get strong typing against the PreviousPage property. You can use the @ PreviousPageType directive only on a Web Forms page (an .aspx file). If both attributes, TypeName and VirtualPath, are defined, the @ PreviousPageType directive will fail.
Example: 7. Application Directive: The Application directive defines application-specific attributes. It is provided at the top of the global.asax file. Application directives specify optional application-specific settings used by the ASP.NET parser when processing ASP.NET global application (.asax) files. Application directives are located at the top of the Global.asax file. Note that the @ Application directive can be used only in Global.asax files, while the other directives are used in other ASP.NET files such as Web pages (.aspx files) and user controls (.ascx files). Application Directive supports following attributes: Language, Inherits, and CodeBehind. Example: 8. Assembly Directive: The @ Assembly directive links an assembly to the page or the application at parse time. This could appear either in the global.asax file for application-wide linking, in the page file, a user control file for linking to a page or user control. OR Links an assembly to an ASP.NET application file (such as a Web page, a user control, a master page, or a Global.asax file) during compilation, making all the assembly's classes and interfaces available for use.
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 31
This directive supports the two attributes Name and Src. The Name attribute defines the assembly name (The assembly name does not include a file name extension) and the Src attribute defines the path to a source file to dynamically compile and link against.
Note: You must include either a Name or a Src attribute in a @ Assembly directive, but you cannot include both within the same directive. If you need to use both of these attributes, you must include multiple @ Assembly directives in the file. Example: 9. Implements Directive: The @ Implements Directive gets the ASP.NET pages to implement .Net framework interfaces. This directive only supports a single attribute i.e. Interface. OR
The Implement directive indicates that the web page, master page or user control page must implement the specified .Net framework interface. Example: 10.Reference Directive:
The Reference directive indicates that another page or user control should be dynamically compiled and linked against the current ASP.NET file (Web page, user control, or master page) in which this directive is declared. Attributes: Page: The external page that ASP.NET should dynamically compile and link to the current file that contains the @ Reference directive. Control: The external user control that ASP.NET should dynamically compile and link to the current file that contains the @ Reference directive. VirtualPath: The virtual path for the reference. Can be any file type as long as a build provider exists. For example, it would be possible to point to a master page. Example: 11.OutputCache Directive: The OutputCache directive controls the output caching policies of a web page or a user control. Attributes: The very important attributes for the @OutputCache directive are as follows: Duration: The time, in seconds, that the page or user control is cached. Setting this attribute on a page or user control establishes an expiration policy for HTTP responses from the object and will automatically cache the page or user control output. VaryByParam: A semicolon-separated list of strings used to vary the output cache. By default, these strings correspond to a query string value sent with GET method attributes, or a parameter sent using the POST method. When this attribute is set to multiple parameters, the output cache
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 32
contains a different version of the requested document for each combination of specified parameters. Possible values include none, an asterisk (*), and any valid query string or POST parameter name. Example: 12.MasterType Directive: The @MasterType Directive connects a class name to the ASP.NET page for getting strongly typed references or members contained in the specified Master Page. This directive supports the two attributes TypeName and VirtualPath. TypeName sets the name of the derived class from which to get the strongly typed or reference members and VirtualPath sets the location of the page from which these are retrieved. If both attributes, TypeName and VirtualPath, are defined, the @ MasterType directive will fail. Example: 13.WebService Directive: Defines XML Web service specific (.asmx file) attributes used by the ASP.NET parser and compiler. Attributes: Class The WebService directive's Class attribute specifies the name of the class implementing the web service. The Class attribute is required. The class specified can reside either in a separate code-behind file, or in-line in the .asmx file. CodeBehind Specifies the source file implementing the XML Web service, when the class implementing the XML Web service does not reside in the same file. Debug Indicates whether the XML Web service should be compiled with debug symbols. True if the XML Web service should be compiled with debug symbols; otherwise, false. Language Specifies the language used when compiling all inline code within the XML Web service file (.asmx). The values can represent any .NET-supported language, including C#, and VB, which refer to Visual C#, and Visual Basic .NET respectively. Example:
Hello ASP.NET"); }
UnLoad This is the last event that gets fired. This is the page cleaning process like closing the open file connections etc., so in this process you cannot do any kind of manipulation with data that affect the rendering, you are restricted to use Response object also, and doing such you will get an exception message. Clean-up can be performed on following:(a) Instances of classes i.e. objects (b) Closing opened files (c) Closing database connections. This event can be handled by overriding the OnUnload method or creating a Page_ Unoad handler as following: protected override void OnUnload (EventArgs e) { base.OnUnload (e); } OR protected void Page_Unload (object sender, EventArgs e) { }
Working with PostBacks: All the web applications are running on Web Servers. Whenever a user made a request to the web server, the web server has to return the response to the user. PostBack is the name given to the process of submitting all the information that the user is currently working on and send it all back to the server. Postback is actually sending all the information from client to web server, then web server process all those contents and returns back to client. A postback originates from the client side browser. When the web page and its contents are sent to the web server for processing some information and then, the web server posts the same page back to the client browser. Normally one of the controls event (e.g. button click) on the page can initiate a postback. Then the state of this control and all other controls on the page is Posted Back to the web server. PostBack is the name given to the process of submitting an ASP.NET page to the server for processing. “A postback is just that a posting back to the same page. The postback contains all the form information collected on the initial page for processing if required.”
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 46
In Classic ASP, developers had their pages post to other pages within the application. ASP.NET pages typically post back to themselves to process events (such as a button control’s click event). For this reason, we must differentiate between posts for the first time a page is loaded by the end user and postbacks. The Page class includes a property called the IsPostBack property, which we can use to detect whether a request is the first instance for a particular page or is a postback from the same page. “IsPostBack Property gets a Boolean value that indicates whether the page is being rendered for the first time or is being loaded in response to a postback.” true if the page is being loaded in response to a client postback; otherwise, false. IsPostBack is normally used on Page_Load event to detect if the web page is getting generated due to postback requested by a control on the page or if the page is getting loaded for the first time. protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { // Do Processing When a Page is Loaded First Time without PostBack } else { // Process Submitted Data with PostBack } }
Cross-Page Posting: Cross Page PostBack in ASP.NET: Cross-page posting is desired in a scenario where data is collected on one Web page and processed on another Web page. ASP.NET 2.0 introduces a new property in the Page class called ‘PreviousPage’ which gets the page that posted to the current page. Normally we use the term postback when an ASP.NET page submits its content back to that page itself. But there can be situation when a page needs to submit its content to a different target page. This is known as cross page postback. ASP.NET by default, submits the form to the same page. Cross page posting is submitting the form to a different page. This is usually required when you are creating a multi-page form to collect information from the user on each page. When moving from the source to the target page, the values of controls in the source page can be accessed in the target page. "To use cross-page posting, you have to use the "PostBackUrl" attribute to specify the page we want to post". Cross Page posting is used to submit a form on one page (say Default.aspx) and retrieve values of controls of this page on another page (say Default2.aspx). To determine whether the page was invoked from a cross-page posting the Page class exposes a property named IsCrossPagePostBack returns either true or false.
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 47
Getting Information from the Source Page: When you configure a page for cross-page posting, you frequently want to get information from the source page. This might include the information from controls on the page—that is, the information being posted by the browser—as well as public properties of the source page.
Getting Control Values The Page class exposes a property named PreviousPage. If the source page and target page are in the same ASP.NET application, the PreviousPage property in the target page contains a reference to the source page. (If the page is not the target of a cross-page posting, or if the pages are in different applications, the PreviousPage property is not initialized.) By default, the PreviousPage property is typed as Page. Using the reference in the PreviousPage property, you can search for controls on the source page and extract their value. You typically do this with the FindControl method. Note: If you are coding the source page specifically to be able to share information with target pages, an easier way to make control values available to the target page is to expose them as public properties. The following code example shows how you can get the value of the TextBox1 control on the source page.
if (Page.PreviousPage != null && PreviousPage.IsCrossPagePostBack) { TextBox SourceTextBox = (TextBox)Page.PreviousPage.FindControl("TextBox1"); if (SourceTextBox != null) { Label1.Text = SourceTextBox.Text; } } Note that if the current page is not the target of a cross-page post, the PreviousPage property returns null (Nothing in Visual Basic).
Getting Public Property Values from the Source Page In the target page of a cross-page posting, you can also get the values of public members of the source page. The most common scenario is that the source page defines public properties and you want to get their values on the target page. To get public members of the source page, you must first get a strongly typed reference to the source page. You can do so in a number of ways. The first is to include a @ PreviousPageType directive in the target page, which allows you to specify the source page, as in this example: When this directive is included, the PreviousPage property is strongly typed to the class of the referenced source page. As a consequence, you can directly reference public members of the source page. You can specify the type of the source page either directly, using a type attribute, or indirectly by explicitly referencing the source page in a VirtualPath attribute, as shown in the above example. The following code example shows a portion of a source page containing a public property named FirstName that exposes the value of a TextBox control named txtFirstName.
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 48
public String FirstName { get { return txtFirstName.Text.Trim(); } } Note: Properties on the source page that are created primarily to expose values for cross-page posting are usually read-only properties. Although the source page can contain public read/write properties, setting a source page property from the target page property generally has no purpose, because the value will not be persisted. If the target page contains a PreviousPageType directive that points to the source page, you can access the source page's FirstName property using code such as the following. Label1.Text = PreviousPage.FirstName; Examples: There are two ways we can use cross page postbacks in ASP.NET 1st Method In this I’ve created a Default.aspx page with two textbox and one button , button click will post back to Default2.aspx and there we will retrieve and show values of both textboxes
Default.aspx: Source View: Cross Page PostBack Example First Name: Last Name: Note: Don't forget to set PostBackUrl Property of Button PostBackUrl="~/Default2.aspx"
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 49
Design View:
Now to retrieve values of textboxes on Default2.aspx page, write below mentioned code in Page_Load event of second page (Default2.aspx) Code File (Default2.aspx.cs): using using using using using using
System; System.Collections.Generic; System.Linq; System.Web; System.Web.UI; System.Web.UI.WebControls;
public partial class Default2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //Check whether previous page is cross page post back or not if (PreviousPage != null && PreviousPage.IsCrossPagePostBack) { TextBox txtFirstName = (TextBox)PreviousPage.FindControl("txtFirstName"); TextBox txtLastName = (TextBox)PreviousPage.FindControl("txtLastName"); Response.Write("Your First Name: " + txtFirstName.Text.Trim()); Response.Write(""); Response.Write("Your Last Name: " + txtLastName.Text.Trim()); } else { Response.Redirect("Default.aspx"); } } } 2nd Method Using Property to expose and consume values of TextBox: If we are using this method then we don't need to use FindControl method at all For this we need to create property in code behind of the page to be cross page post back (Default.aspx)
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 50
Html of the page (Default.aspx) needs no changes, C# code behind for Default.aspx:
Code File (Default.aspx.cs): using using using using using using
System; System.Collections.Generic; System.Linq; System.Web; System.Web.UI; System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } public TextBox pbTxtFirstName { get { return txtFirstName; } }
}
public TextBox pbTxtLastName { get { return txtLastName; } }
Now to retrieve or consume exposed properties on Second page we need to add below mentioned page directive in html source of Default2.aspx page (usually at the top of page) Now write this code in Page_Load event of second page to retrieve values of controls C# Code
Code File (Default2.aspx.cs): using using using using using
System; System.Collections.Generic; System.Linq; System.Web; System.Web.UI; Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved.
P a g e | 51
using System.Web.UI.WebControls; public partial class Default2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //Check whether previous page is cross page post back or not if (PreviousPage != null && PreviousPage.IsCrossPagePostBack) { Response.Write("Your First Name: " + PreviousPage.pbTxtFirstName.Text.Trim()); Response.Write(""); Response.Write("Your Last Name: " + PreviousPage.pbTxtLastName.Text.Trim()); } else { Response.Redirect("Default.aspx"); } } }
Output:
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 52
Working with ASP.Net Web Forms Controls: Controls are main building blocks of the graphical user interface, which include text boxes, buttons, check boxes, list boxes, labels, and numerous other controls. Using these controls, the users can enter data, make selections and indicate their preferences. Controls are also used for structural jobs, like validation, data access, security, creating master pages, and data manipulation. ASP.NET uses five types of web controls, which are following:
HTML Controls
HTML Server Controls
ASP.NET Server Controls
ASP.NET Ajax Server Controls
User Controls and Custom Controls
HTML Controls: By default, HTML elements on an ASP.NET Web page are not available to the server; they are treated as opaque text that is passed through to the browser. However, by converting HTML elements to HTML server controls, you expose them as elements you can program in server-based code. OR HtmlControls are just programmable HTML tags. By default these tags are literal text and you can't reference them with server side code. To "see" any HTML tag with your ASP.NET server side code you need to add runat="server" and some value to ID parameter. For example, to work with HTML tag with server side code, you can use HTML code like this: By default most commonly used HTML controls (elements) can be viewed in the toolbox of design view of the page in Visual Studio IDE.
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 53
These are following major HTML Controls:
Input (Button): Output:
Input (Reset): Output:
Input (Submit): Output: Input (Text): Output:
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 54
Input (File): Output:
Input (Password): Output:
Input (CheckBox): Select Output:
Input (Radio): Male Female Output:
Input (Hidden): Output: Invisible on the page. Textarea: Output:
Table Output:
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 55
Image Output:
Select: (DropDownList) Select Option1 Option2 Option3 Output:
OR (ListBox) Option1 Option2 Option3 Output:
Horizontal Rule Output: Div Output: It’s Container
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 56
HTML Server Controls: The HTML server controls are Hypertext Markup Language (HTML) elements that include a runat=server attribute. The HTML server controls have the same HTML output and the same properties as their corresponding HTML tags. OR The HTML server controls are basically the standard HTML controls enhanced to enable server side processing. The HTML controls such as the header tags, anchor tags, and input elements are not processed by the server but are sent to the browser for display. They are specifically converted to a server control by adding the attribute runat="server" and adding an id attribute to make them available for server-side processing. For example, consider the HTML input control: It could be converted to a server control, by adding the runat and id attribute:
In addition, HTML server controls provide automatic state management and server-side events. HTML server controls offer the following advantages:
The HTML server controls map one to one with their corresponding HTML tags.
When the ASP.NET application is compiled, the HTML server controls with the runat=server attribute are compiled into the assembly.
Most controls include an OnServerEvent for the most commonly used event for the control. For example, the control has an OnServerClick event.
When the ASP.NET page is reposted, the HTML server controls keep their values.
Note: All HTML server controls must be within a tag with the runat="server" attribute. The runat="server" attribute indicates that the form should be processed on the server. It also indicates that the enclosed controls can be accessed by server scripts. All HTML elements mapped to a corresponding classes in ASP.NET that represents as server control to use programmatically. HTML control classes found in the System.Web.UI.HtmlControls namespace. HtmlControl is a base class for all HTML server controls containing all of the common properties. The System.Web.UI.HtmlControls namespace contains classes that allow you to create HTML server controls on a Web Forms page. HTML server controls run on the server and map directly to standard HTML tags supported by most browsers. This allows you to programmatically control the HTML elements on a Web Forms page.
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 57
These are following HTML server controls classes that are available in ASP.NET: Class
Description
HtmlAnchor
Allows programmatic access to the HTML element on the server.
HtmlArea
Provides programmatic access to the HTML element on the server.
HtmlAudio
Provides programmatic access to the HTML element on the server.
HtmlButton
Allows programmatic access to the HTML tag on the server.
HtmlContainerControl
Serves as the abstract base class for HTML server controls that map to HTML elements that are required to have an opening and a closing tag.
HtmlControl
Defines the methods, properties, and events common to all HTML server controls in the ASP.NET page framework.
HtmlElement
Provides programmatic access to the document's element on the server, which represents the document's root.
HtmlEmbed
Provides programmatic access to the HTML embed element on the server.
HtmlForm
Provides programmatic access to the HTML element on the server.
HtmlGenericControl
Defines the methods, properties, and events for all HTML server control elements not represented by a specific .NET Framework class.
HtmlHead
Provides programmatic access to the HTML head element in server code.
HtmlIframe
Provides programmatic access to the HTML element on the server.
HtmlImage
Provides programmatic access for the HTML element on the server.
HtmlInputButton
Allows programmatic access to the HTML , , and elements on the server.
HtmlInputCheckBox
Allows programmatic access to the HTML element on the server.
HtmlInputControl
Serves as the abstract base class that defines the methods, properties, and events common to all HTML input controls, such as the , , and elements.
HtmlInputFile
Allows programmatic access to the HTML element on the server.
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 58
HtmlInputGenericControl
Defines the methods, properties, and events for server-side access to the HTML5 input element.
HtmlInputHidden
Allows programmatic access to the HTML element on the server.
HtmlInputImage
Allows programmatic access to the HTML element on the server.
HtmlInputPassword
Allows programmatic access to the HTML element on the server.
HtmlInputRadioButton
Allows programmatic access to the HTML element on the server.
HtmlInputReset
Allows programmatic access to the HTML element on the server.
HtmlInputSubmit
Allows programmatic access to the HTML element on the server.
HtmlInputText
Allows programmatic access to the HTML and elements on the server.
HtmlLink
Allows programmatic access to the HTML link element on the server.
HtmlMeta
Allows programmatic access to the HTML tag on the server.
HtmlSelect
Allows programmatic access to the HTML element on the server.
HtmlTable
Allows programmatic access on the server to the HTML element.
HtmlTableCell
Represents the and HTML elements in an HtmlTableRow object.
HtmlTableCellCollection
A collection of HtmlTableCell objects that represent the cells in a single row of an HtmlTable control. This class cannot be inherited.
HtmlTableRow
Represents the HTML element in an HtmlTable control.
HtmlTableRowCollection
A collection of HtmlTableRow objects that represent the rows of an HtmlTable control. This class cannot be inherited.
HtmlTextArea
Allows programmatic access to the HTML element on the server.
HtmlTitle
Allows programmatic access to the HTML element on the server.
HtmlVideo
Provides programmatic access to the HTML element on the server.
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 59
Creating HTML Server Controls Programmatically: In order to create HTML Server Controls programmatically, you need to use the following steps: Steps: Step1: Import the corresponding namespace in which all the html control classes found i.e. System.Web.UI.HtmlControls Step2: Declare the control class object Step3: Instantiate the control class object Step4: Set the possible properties values which are required Step5: Add the event handlers & their event definition if required Step6: Add the control object to a form container For Example: Creating an HTML Input TextBox & Button Control with ServerClick Event Handler Programmatically: Code File: Default.aspx.cs: using using using using using using
System; System.Collections.Generic; System.Linq; System.Web; System.Web.UI; System.Web.UI.WebControls;
using System.Web.UI.HtmlControls; public partial class Default : System.Web.UI.Page { HtmlGenericControl span1; HtmlInputText text1; HtmlInputButton button1; HtmlGenericControl span2; protected void Page_Load(object sender, EventArgs e) { this.span1 = new HtmlGenericControl("span"); this.span1.InnerHtml = "Enter Text Here:"; this.span1.Attributes["style"] = "color:green"; this.text1 = new HtmlInputText(); this.text1.Attributes["style"] = "background-color:yellow;color:blue"; this.button1 = new HtmlInputButton(); this.button1.Value = "Submit"; this.button1.Attributes["style"] = "background-color:green;color:white"; this.button1.ServerClick += new EventHandler(button1_Click); this.span2 = new HtmlGenericControl("span"); this.form1.Controls.Add(this.span1); this.form1.Controls.Add(this.text1); this.form1.Controls.Add(this.button1); this.form1.Controls.Add(this.span2); } protected void button1_Click(object sender, EventArgs e) { this.span2.InnerHtml = "" + "Your Entered Text: " + this.text1.Value; } }
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 60
Output:
ASP.NET Server Controls: The ASP.NET page framework includes a number of built-in server controls that are designed to provide a more structured programming model for the Web. ASP.NET Server controls are specifically designed to work with Web Forms pages. Web server controls include traditional form controls such as buttons and text boxes as well as complex controls such as tables. They also include controls that provide commonly used form functionality such as displaying data in a grid, choosing dates, displaying menus, and so on. Web server controls offer all of the features described above for HTML server controls (except one-to-one mapping to elements) and these additional features:
Automatic state management. A rich object model that provides type-safe programming capabilities. Automatic browser detection. The controls can detect browser capabilities and render appropriate markup. For some controls, the ability to define your own layout for the control using Templates. For some controls, the ability to specify whether a control's event causes immediate posting to the server or is instead cached and raised when the page is submitted. Support for themes, which enable you to define a consistent look for controls throughout your site. Ability to pass events from a nested control (such as a button in a table) to the container control. Ability to react to events in server-side code to create applications that are better structured. Common approach to building user interfaces for Web pages. Output is automatically customized based on the capabilities of the browser.
Note: Like HTML server controls, Web server controls are also created on the server and they require a runat="server" attribute to work. However, Web server controls do not necessarily map to any existing HTML elements and they may represent more complex elements. The controls use syntax declaratively such as the following: The attributes in this case are not those of HTML elements. Instead, they are properties of the Web control. Example: When the ASP.NET Web page runs, the Web server control is rendered on the page using appropriate markup, which often depends not only on the browser type but also on settings that you have made for the control. For example, a TextBox control might render as an input tag or a textarea tag, depending on its properties.
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 61
ASP.NET includes a large selection of Web server controls that you can use on ASP.NET Web pages, divided into following categories:
Standard ASP.NET Web Server Controls
Intrinsic Controls (Basic Controls) o o o o o o o o o o o o o o o o o o o o
Advanced Controls: o o o o o o
ImageMap Calendar AdRotator View MultiView Wizard
Validation Controls:
Label TextBox Button LinkButton ImageButton CheckBox RadioButton DropDownList ListBox CheckBoxList RadioButtonList BulletedList Image Hyperlink FileUpload Literal HiddenField PlaceHolder Panel Table
RequiredFieldValidator RangeValidator CompareValidator RegularExpressionValidator CustomValidator ValidationSummary
Navigation Controls:
Menu TreeView SiteMapPath
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 62
Data Controls (Data-Bound Controls):
Repeater DataList GridView DetailsView FormView ListView
o
Data Source Controls:
o o o
SqlDataSource ObjectDataSource AccessDataSource XmlDataSource SiteMapDataSource LinqDataSource EntityDataSource DataPager Chart QueryExtender
Login Controls:
Login LoginName LoginStatus LoginView PasswordRecovery ChangePassword CreateUserWizard
CrystalReportViewer ReportViewer
Reporting Controls:
Note:
All ASP.NET Web Server Controls mapped to a corresponding classes found in the System.Web.UI.WebControls namespace. WebControl is a base class for all ASP.NET Web Server Controls containing all of the common properties. The System.Web.UI.WebControls namespace contains classes that allow you to create ASP.NET web server controls on a Web Forms page. This allows you to programmatically control the ASP.NET Web Server elements on a Web Forms page. Control class is an ultimate base class for all ASP.NET Web Server Controls and HTML Server Controls and all the control classes found in the default assembly of an ASP.NET Web Form Page Framework i.e. System.Web.dll library assembly.
Creating ASP.NET Web Server Controls Programmatically: In order to create ASP.NET Web Server Controls programmatically, you need to use the following steps: Steps: Step1: Import the corresponding namespace in which all the ASP.NET Web Server Control classes found i.e. System.Web.UI.WebControls Step2: Declare the control class object Step3: Instantiate the control class object Step4: Set the possible properties values which are required Step5: Add the event handlers & their event definition if required Step6: Add the control object to a form container
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 63
For Example: Creating an ASP.NET Label, TextBox & Button Control with Click Event Handler Programmatically: Code File: Default.aspx.cs: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class Default : System.Web.UI.Page { Label label1; TextBox textbox1; Button button1; Label label2; protected void Page_Load(object sender, EventArgs e) { this.label1 = new Label(); this.label1.Text = "Enter Name: "; this.label1.Font.Bold = true; this.label1.ForeColor = System.Drawing.Color.Blue; this.textbox1 = new TextBox(); this.textbox1.BackColor = System.Drawing.Color.Yellow; this.button1 = new Button(); this.button1.Text = "Submit"; this.button1.Click += new EventHandler(button1_Click); this.label2 = new Label(); this.form1.Controls.Add(this.label1); this.form1.Controls.Add(this.textbox1); this.form1.Controls.Add(this.button1); this.form1.Controls.Add(this.label2); } protected void button1_Click(object sender, EventArgs e) { this.label2.Text = "" + "Your Name Is: " + this.textbox1.Text.Trim(); } }
Output:
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 64
ASP.NET Ajax Server Controls: ASP.NET Ajax server controls that enable you to add Ajax functionality to an ASP.NET Web page. Ajax functionality includes re-rendering parts of a page with a partial-page update and therefore avoiding a full-page postback.
ASP.NET AJAX Extension o
ScriptManager
o
ScriptManagerProxy
o
UpdatePanel
o
UpdateProgress
o
Timer
Note: All ASP.NET Ajax Server Controls are extension controls to enable Ajax functionality in a web form mapped
to
a
corresponding
classes
found
in
the
System.Web.UI
namespace
&
System.Web.Extension.dll library assembly. Control is a base class for all ASP.NET Ajax Server Controls containing all of the common properties.
User Controls and Custom Controls: In addition to the built-in controls, the ASP.NET page framework also provides the ability to create user controls and custom controls. User controls and custom controls can enhance and extend existing controls to build a much richer user interface.
User Controls: Often, you may want to reuse the user interface of your Web Form without having to write any extra code. ASP.NET enables you to do this by converting your Web Forms into user controls. User controls, which have the .ascx file extension, can be used multiple times within a single Web Form.
Custom Controls: In addition to the built-in Web controls, ASP.NET also allows you to create your own custom controls. It may be useful to develop custom controls if you are faced with one of these scenarios: You need to combine the functionality of two or more built-in Web controls. You need to extend the functionality of a built-in control. You need a control that is completely different than any of the controls that currently exist.
Copyright © 2015 https://www.facebook.com/rakeshdotnet All Rights Reserved. P a g e | 65
View more...
Comments