Rakesh Singh
NARESH I TECHNOLOGIES Hyderabad
ASP.NET – Web Forms Code
Framework Development
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 arestateless. 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 createall 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.
.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
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
Default.aspx
Default.aspx.cs
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:
<%@PageLanguage="C#"AutoEventWireup="true"CodeFile="Default.aspx.cs"Inherits="Default" %> <!DOCTYPEhtml>
<html>
<headrunat="server">
<title>ASP.NET Web Site</title> <script type="text/javascript"> function validate() {
var firstName = document.getElementById("TextBox1").value; var lastName = document.getElementById("TextBox2").value; var error = "";
if (firstName == "")
error += "Please Enter First Name" + "\n"; if (lastName == "")
error += "Please Enter Last Name" + "\n"; if (error != "") { alert(error); returnfalse; } } </script> </head>
<bodystyle="background-color: Azure"> <form id="form1"runat="server">
<asp:ImageID="Image1"runat="server" ImageUrl="Images/Ads1.jpg" Width="99%"
Height="150"AlternateText="Image Control"ToolTip="Image Banner"BorderStyle="Dotted"
BorderWidth="5"BorderColor="Green" />
<marqueedirection="right"style="background-color: yellow; color: green; font-size: 25px; border: 5pxsolidred">
<h1>Welcome to ASP.NET Web Site</h1> </marquee>
<hr/>
Image Used in Web Form
Web Form - UI
Web Form – Code File
<asp:LabelID="Label1"runat="server" Text="Enter First Name: "Font-Size="15"Font-Bold="True"
ForeColor="Blue"/>
<asp:TextBoxID="TextBox1"runat="server" /> <br/>
<br/>
<asp:LabelID="Label2"runat="server" Text="Enter Last Name: "Font-Size="15" Font-Bold="True"ForeColor="Blue"/>
<asp:TextBoxID="TextBox2"runat="server" /> <br/>
<br/>
<asp:ButtonID="Button1"runat="server" Text="Submit"OnClientClick="return validate();"
OnClick="Button1_Click"/> <br/>
<asp:LabelID="Label3"runat="server" /> </form>
</body> </html>
Default.aspx.cs (Code File):
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls;public partialclassDefault : System.Web.UI.Page {
protectedvoid Page_Load(object sender, EventArgs e) {
TextBox1.Focus(); }
protectedvoid Button1_Click(object sender, EventArgs e) {
string firstName = TextBox1.Text.Trim(); string lastName = TextBox2.Text.Trim(); string fullName = firstName + " " + lastName; Label3.Text="<b>Your Name Is: </b>" + 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 Site3. 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:
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)
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 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.
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.
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.
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 file-system 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 IIS
Web site 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
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. FTP Web site
project
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:
<?xml version="1.0"?>
For more information on how to configure your ASP.NET application, please visit http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration> <system.web>
<compilation debug="false"targetFramework="4.5"/> <httpRuntime targetFramework="4.5"/>
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:-
<%@PageLanguage="C#"AutoEventWireup="true"CodeFile="Default.aspx.cs"Inherits="_Default" %> <!DOCTYPEhtml>
<htmlxmlns="http://www.w3.org/1999/xhtml"> <headrunat="server">
<title></title> </head>
<body>
<form id="form1"runat="server"> <div> </div> </form> </body> </html> 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 partialclass_Default : System.Web.UI.Page {
protectedvoid Page_Load(object sender, EventArgs e) {
} }
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.
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.
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.
The following table summarizes the main differences:
Web application projects Web site projects
Project file structure
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.
Compilation 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.
Visual Studio provides tools that integrate with Web Deploy (the IIS web deployment tool) to automate many deployment tasks.
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.
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.
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 <script runat=”server”> 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 Created File Extension Web Form .aspx file
Master Page .master file Web User Control .ascx file Web Services .asmx file
Default.aspx:
<%@PageLanguage="C#" %> <!DOCTYPEhtml>
<scriptrunat="server">
protectedvoid 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 newDivideByZeroException("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; }
}
protectedvoid btnAdd_Click(object sender, EventArgs e) {
Calc("+"); }
protectedvoid btnSub_Click(object sender, EventArgs e) {
Calc("-"); }
protectedvoid btnMul_Click(object sender, EventArgs e) {
Calc("*"); }
protectedvoid btnDiv_Click(object sender, EventArgs e) {
Calc("/"); }
</script>
<htmlxmlns="http://www.w3.org/1999/xhtml"> <headrunat="server">
<title></title>
<script type="text/javascript"> 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); returnfalse; } } </script> </head> <body>
<form id="form1"runat="server">
<h1style="text-align: center; color: maroon">Inline Code Model Example </h1>
<divalign="center">
<asp:LabelID="lblStatus"runat="server" ForeColor="Red"/> <br/>
<br/>
<b>Enter Value1:</b><asp:TextBox ID="txtValue1" runat="server"/> <br/>
<b>Enter Value2:</b><asp:TextBox ID="txtValue2" runat="server"/> <br/>
<br/>
<asp:Button ID="btnAdd"runat="server"Text="Add"OnClientClick="return validate();"
OnClick="btnAdd_Click"/>
<asp:Button ID="btnSub"runat="server"Text="Sub" OnClientClick="return validate();"
OnClick="btnSub_Click"/>
<asp:Button ID="btnMul" runat="server"Text="Mul"OnClientClick="return validate();"
OnClick="btnMul_Click"/>
<asp:Button ID="btnDiv"runat="server" Text="Div"OnClientClick="return validate();"
OnClick="btnDiv_Click" /> <br/>
<br/>
<b>Result:</b><asp:TextBoxID="txtResult"runat="server" ReadOnly="true"/> </div>
</form> </body> </html> Note:
We can see that all the business logic is encapsulated in between <script runat=”server”> 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
Created File Extension Web Form .aspx file
.aspx.cs file or .aspx.vb file Master Page .master file
.master.cs file or .master.vb file Web User Control .ascx file
.ascx.cs file or .ascx.vb file Web Services .asmx file
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:
<%@PageLanguage="C#"AutoEventWireup="true"CodeFile="Default2.aspx.cs"Inherits="Default2" %>
<!DOCTYPEhtml>
<htmlxmlns="http://www.w3.org/1999/xhtml"> <headrunat="server">
<title></title>
<script type="text/javascript"> 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" + "<br />"; if (value2 == "")
error += "Please Enter Value2" + "<br />"; if (error != "") {
document.getElementById("lblError").innerHTML = error; returnfalse; } else { __doPostBack(event, ""); returntrue; }
else {
document.getElementById("lblError").innerHTML = "Please Select Any Option!!!"; returnfalse; } } </script> </head> <body>
<form id="form1"runat="server">
<h1style="text-align: center; color: maroon">Code Behind Model Example</h1> <divalign="center">
<asp:LabelID="lblError" runat="server"ForeColor="Red"/> <br/>
<br/>
<b>Enter Value1:</b><asp:TextBox ID="txtValue1" runat="server"/> <br/>
<br/>
<b>Enter Value2:</b><asp:TextBox ID="txtValue2" runat="server"/> <br/>
<br/>
<b>Select Option:</b>
<asp:DropDownList ID="ddlCalc" runat="server" AutoPostBack="true"onchange="return validate(this.value);" OnSelectedIndexChanged="ddlCalc_SelectedIndexChanged">
<asp:ListItemText="Select"Value=""/> <asp:ListItemText="Add"Value="+"/> <asp:ListItemText="Sub"Value="-"/> <asp:ListItemText="Mul"Value="*" /> <asp:ListItemText="Div"Value="/"/> </asp:DropDownList>
<br/> <br/>
<b>Result:</b><asp:TextBoxID="txtResult"runat="server" ReadOnly="true"/> </div>
</form> </body> </html>
Code File (Default2.aspx.cs): using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls;
public partialclassDefault2 : System.Web.UI.Page {
protectedvoid Page_Load(object sender, EventArgs e) {
txtValue1.Focus(); }
{
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)
thrownewDivideByZeroException("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.
Difference between Inline code and Code-behind.
Inline Code Code Behind
The business logic is in <script> blocks in the same
.aspx file that contains the HTML and controls. The HTML and controls are in the .aspx file, and the business logic is in a separate .aspx.cs or .aspx.vb file.
When the page is deployed, the source code is deployed along with the Web Forms page, since it is physically in the .aspx file. Though, we are not able to see the code, only the results are rendered when the page runs.
All project class files (without the .aspx file) are compiled into a .dll file, which are deployed to the server without any source code. When a request for the page is received, then an instance of the project .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 same page with Html code between scripting tags. So Each time when there is a request for page it compiles the code each time then server the page Like classic asp because inline code cannot create dll.
The code-behind approach also improved productivity (at some level) since the designer and the developer can continue working simultaneously on the same set of application.
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).
@ 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 cross-page 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: <%@ DirectiveName Attribute=Value %>
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
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 <title> 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.
Syntax:
<%@ Page attribute="value" [attribute="value"...] %>
For Example:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
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:
<%@ Master attribute="value" [attribute="value"...] %>
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:
<%@ Control attribute="value" [attribute="value"...] %>
Example:
<%@ Control Language="C#" AutoEventWireup="false" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>
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