ASP.NET Tutorial
ASP.NET Web Forms
ASP.NET Web Forms is a web application framework developed by Microsoft as part of the .NET Framework. It allows developers to build dynamic web sites and applications using a familiar drag-and-drop interface and a code-behind model that separates business logic from presentation. ASP.NET Web Forms is a powerful tool for building complex web applications with minimal code.
ASP.NET WF Introduction
ASP.NET Web Forms (WF) provides a visual and event-driven programming model for building web applications. It abstracts the complexities of the HTML and HTTP protocols, allowing developers to focus on building the functionality of the application without worrying about the intricacies of client-server communication. Using a rich set of server controls and state management features, Web Forms simplifies the creation of web pages that are both interactive and data-driven.
- Allows for rapid development using a drag-and-drop interface.
- Built-in controls like GridView, FormView, and DataList for data handling.
- Supports server-side programming with languages like C# and VB.NET.
- Provides a robust event-driven programming model similar to Windows Forms.
ASP.NET WF Features
ASP.NET Web Forms comes with a variety of features that make it a powerful tool for developing web applications. Here's a look at some of its key features:
- Server Controls: A rich library of pre-built controls like TextBox, Button, DropDownList, GridView, etc., which handle the rendering of HTML and manage server-side events.
- View State: Maintains the state of server controls between postbacks without having to rely on client-side state management.
- Event-Driven Programming: Supports event-driven development, allowing developers to handle events like button clicks or dropdown selections directly in the code-behind.
- Master Pages: Provides a template-based layout mechanism that ensures a consistent look and feel across all pages in an application.
- Data Binding: Simplifies data manipulation by binding controls to various data sources such as databases, XML, or custom objects.
- Security: Built-in support for authentication, authorization, and role-based access control.
Creating an ASP.NET WF Project
To create a new ASP.NET Web Forms project, follow these steps:
- Open Visual Studio and select Create a new project.
- Choose ASP.NET Web Application (.NET Framework) and click Next.
- Name the project, choose a location, and select the desired framework version (e.g., .NET Framework 4.8).
- Choose Web Forms as the template and click Create.
After creating the project, Visual Studio will generate the default files for you, including a sample master page, content page, and default ASPX file.
ASP.NET WF Example
Let's create a simple example of an ASP.NET Web Form that displays a list of users in a GridView and allows adding a new user. Here's a breakdown of the code:
Design the Web Form (ASPX)
< %@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default" %>
< !DOCTYPE html>
< html xmlns="http://www.w3.org/1999/xhtml">
< head runat="server">
< title>User Management
< /head>
< body>
< form id="form1" runat="server">
< div>
< asp:Label ID="lblMessage" runat="server" Text="">< /asp:Label>
< asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="false">
< Columns>
< asp:BoundField DataField="Id" HeaderText="User ID" />
< asp:BoundField DataField="Name" HeaderText="User Name" />
< /Columns>
< /asp:GridView>
< asp:TextBox ID="txtUserName" runat="server">< /asp:TextBox>
< asp:Button ID="btnAddUser" runat="server" Text="Add User" OnClick="btnAddUser_Click" />
< /div>
< /form>
< /body>
< /html>
Code-Behind (C#)
// Default.aspx.cs
using System;
using System.Collections.Generic;
public partial class Default : System.Web.UI.Page
{
// Simple in-memory user list for demonstration
private static List< User> userList = new List< User>();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridView();
}
}
protected void btnAddUser_Click(object sender, EventArgs e)
{
string userName = txtUserName.Text.Trim();
if (!string.IsNullOrEmpty(userName))
{
// Add new user to the list
userList.Add(new User { Id = userList.Count + 1, Name = userName });
BindGridView();
lblMessage.Text = "User added successfully!";
}
else
{
lblMessage.Text = "Please enter a user name.";
}
}
private void BindGridView()
{
// Bind the GridView to the user list
gvUsers.DataSource = userList;
gvUsers.DataBind();
}
}
// User class to represent the user data
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
In the example above, we have a basic user management form where users can be added to an in-memory list. The list is then displayed in a GridView. This example demonstrates the simplicity of ASP.NET Web Forms for managing form-based interactions.
ASP.NET Label Control
The Label control in ASP.NET is used to display static or dynamic text on a webpage. It is a lightweight control that is often used to show validation messages, information, or any other content that doesn’t require user interaction.
Label Example
< asp:Label ID="lblMessage" runat="server" Text="Welcome to ASP.NET!" Font-Bold="True" Font-Size="Large">< / asp:Label>
In this example, the `Label` control displays a welcome message. The `runat="server"` attribute indicates that this control is processed on the server.
ASP.NET TextBox Control
The TextBox control allows users to input text on a webpage. It is a versatile control that can be used for simple text entry, passwords, numbers, or any other user inputs. The TextBox supports different modes such as single-line, multi-line, and password.
TextBox Example
< asp:TextBox ID="txtName" runat="server" Width="200px" Placeholder="Enter your name">< /asp:TextBox>
In this example, a `TextBox` is created for the user to enter their name. The `Placeholder` attribute gives a hint to the user about what to enter in the field.
TextBox Properties
- Text: Gets or sets the content of the TextBox.
- TextMode: Specifies the type of input (SingleLine, MultiLine, or Password).
- MaxLength: Limits the number of characters the user can enter.
- ReadOnly: Specifies whether the TextBox is read-only.
ASP.NET Button Control
The Button control is a standard ASP.NET server control that triggers events on the server when clicked by the user. It is commonly used to submit forms, initiate actions, or trigger server-side events.
Button Example
< asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
In this example, a `Button` control is created. When clicked, it triggers the `btnSubmit_Click` event handler on the server, allowing you to process the user's action.
Button Event Handler (C#)
// Code-behind for Button Click Event
protected void btnSubmit_Click(object sender, EventArgs e)
{
string name = txtName.Text;
lblMessage.Text = "Hello, " + name + "!";
}
This code-behind example shows how to handle the `Button` click event. When the user clicks the button, the `btnSubmit_Click` method reads the user's input from the `TextBox` and displays a greeting message in the `Label`.
Example Form with ASP.NET Server Controls
Below is a more complete example using the ASP.NET `Label`, `TextBox`, and `Button` controls together in a simple form:
< form id="form1" runat="server">
< div>
< asp:Label ID="lblMessage" runat="server" Text="" Font-Italic="True" ForeColor="Green">
< br />
< asp:Label ID="lblName" runat="server" Text="Enter your name:">< /asp:Label>
< asp:TextBox ID="txtName" runat="server" Width="250px">< /asp:TextBox>
< br /> < br />
< asp:Button ID="btnSubmit" runat="server" Text="Greet Me" OnClick="btnSubmit_Click" />
< /div>
< /form>
Code-Behind (C#)
// Code-behind for the ASP.NET Form
protected void btnSubmit_Click(object sender, EventArgs e)
{
string name = txtName.Text;
if (!string.IsNullOrEmpty(name))
{
lblMessage.Text = "Welcome, " + name + "!";
}
else
{
lblMessage.Text = "Please enter your name.";
}
}
In this form, the user is prompted to enter their name, which is then greeted with a welcome message when they click the button. The server-side logic is minimal, making the development process straightforward.
ASP.NET HyperLink Control
The HyperLink control in ASP.NET is used to create clickable links that navigate to another web page or resource. It's a simple way to add navigation to your web forms.
HyperLink Example
< asp:HyperLink ID="hlExample" runat="server"
NavigateUrl="https://www.example.com"
Text="Visit Example Website"
Target="_blank">< /asp:HyperLink>
In this example, the `HyperLink` control navigates to an external website when clicked. The `Target="_blank"` attribute opens the link in a new browser tab.
Key Properties of HyperLink
- NavigateUrl: Specifies the URL to navigate to when the link is clicked.
- Text: The text displayed for the hyperlink.
- Target: Specifies where to open the linked document (e.g., "_blank" for a new tab).
ASP.NET RadioButton Control
The RadioButton control is used when you want to allow a user to select only one option from a group. To group radio buttons together, use the `GroupName` property.
RadioButton Example
< asp:RadioButton ID="rbOption1" runat="server"
GroupName="OptionsGroup"
Text="Option 1"
Checked="True" />
< br />
< asp:RadioButton ID="rbOption2" runat="server"
GroupName="OptionsGroup"
Text="Option 2" />
This example shows two `RadioButton` controls grouped by the same `GroupName`. Only one option can be selected at a time within this group.
RadioButton Properties
- GroupName: Groups radio buttons together so that only one can be selected at a time.
- Text: The label displayed next to the radio button.
- Checked: Specifies if the radio button is selected by default.
ASP.NET Calendar Control
The Calendar control provides a way for users to select a date or navigate through months and years. It is ideal for date-related input fields.
Calendar Example
< asp:Calendar ID="calDatePicker" runat="server"
OnSelectionChanged="calDatePicker_SelectionChanged">
< /asp:Calendar>
This `Calendar` control allows the user to pick a date. The `OnSelectionChanged` attribute specifies the event handler triggered when a date is selected.
Code-Behind for Calendar Selection (C#)
// Code-behind for Calendar Selection Event
protected void calDatePicker_SelectionChanged(object sender, EventArgs e)
{
lblSelectedDate.Text = "Selected Date: " + calDatePicker.SelectedDate.ToShortDateString();
}
In this code example, the selected date from the calendar is displayed using a `Label` control when the user chooses a date.
ASP.NET CheckBox Control
The CheckBox control allows users to make a selection of true/false or yes/no. Unlike `RadioButton`, multiple checkboxes can be selected at the same time.
CheckBox Example
< asp:CheckBox ID="chkAgree" runat="server"
Text="I agree to the terms and conditions" />
< br />
< asp:Button ID="btnSubmit" runat="server"
Text="Submit" OnClick="btnSubmit_Click" />
Code-Behind for CheckBox Handling (C#)
// Code-behind for CheckBox Handling
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (chkAgree.Checked)
{
lblMessage.Text = "Thank you for agreeing to the terms.";
}
else
{
lblMessage.Text = "Please agree to the terms before proceeding.";
}
}
This example shows how to handle a `CheckBox` control in ASP.NET. The `Button` click event checks if the checkbox is selected and displays a message accordingly.
ASP.NET LinkButton Control
The LinkButton control in ASP.NET is similar to the `HyperLink` control but it posts back to the server, allowing you to handle events like a regular button. It's used when you need a clickable link that triggers server-side processing.
LinkButton Example
< asp:LinkButton ID="lnkClickMe" runat="server"
Text="Click Me!"
OnClick="lnkClickMe_Click">< /asp:LinkButton>
Code-Behind for LinkButton (C#)
// Code-behind for LinkButton Click Event
protected void lnkClickMe_Click(object sender, EventArgs e)
{
lblMessage.Text = "LinkButton clicked!";
}
In this example, clicking the `LinkButton` triggers a postback, and the server-side event handler updates a message on the page.
Key Properties of LinkButton
- Text: The clickable text displayed on the button.
- OnClick: Specifies the event handler for the click event.
ASP.NET FileUpload Control
The FileUpload control allows users to upload files to the server. It's commonly used for uploading documents, images, or other file types.
FileUpload Example
<!-- Example of ASP.NET FileUpload Control -->
<asp:FileUpload ID="fileUploader" runat="server" />
<br />
<asp:Button ID="btnUpload" runat="server"
Text="Upload File"
OnClick="btnUpload_Click" />
Code-Behind for FileUpload (C#)
// Code-behind for FileUpload Control
protected void btnUpload_Click(object sender, EventArgs e)
{
if (fileUploader.HasFile)
{
string fileName = Server.MapPath("~/Uploads/" + fileUploader.FileName);
fileUploader.SaveAs(fileName);
lblMessage.Text = "File uploaded successfully!";
}
else
{
lblMessage.Text = "Please select a file to upload.";
}
}
This example shows how to handle file uploads using the `FileUpload` control. The `SaveAs` method saves the uploaded file to a specific server directory.
Key Properties of FileUpload
- HasFile: Indicates if a file has been uploaded through the control.
- FileName: The name of the file uploaded.
ASP.NET Multiple FileUpload
To allow multiple files to be uploaded, you can extend the `FileUpload` functionality using HTML5's `multiple` attribute. ASP.NET can handle multiple files using a loop in the server-side code.
Multiple FileUpload Example
<!-- Example of ASP.NET Multiple FileUpload -->
<input type="file" id="multipleFiles" runat="server" multiple="multiple" />
<br />
<asp:Button ID="btnUploadMultiple" runat="server"
Text="Upload Files"
OnClick="btnUploadMultiple_Click" />
Code-Behind for Multiple FileUpload (C#)
// Code-behind for Multiple FileUpload
protected void btnUploadMultiple_Click(object sender, EventArgs e)
{
HttpFileCollection uploadedFiles = Request.Files;
for (int i = 0; i < uploadedFiles.Count; i++)
{
HttpPostedFile file = uploadedFiles[i];
if (file.ContentLength > 0)
{
string fileName = Server.MapPath("~/Uploads/" + file.FileName);
file.SaveAs(fileName);
}
}
lblMessage.Text = "All files uploaded successfully!";
}
In this example, multiple files are processed using a `for` loop, where each file is saved to the server directory using `SaveAs`.
ASP.NET Download File
You can provide a way for users to download files stored on the server using ASP.NET. The `Response` object in ASP.NET allows you to prompt the download of a file.
Download File Example
<!-- Example of ASP.NET Download File -->
<asp:Button ID="btnDownload" runat="server"
Text="Download File"
OnClick="btnDownload_Click" />
Code-Behind for Download File (C#)
// Code-behind for Downloading a File
protected void btnDownload_Click(object sender, EventArgs e)
{
string filePath = Server.MapPath("~/Uploads/sample.pdf");
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=sample.pdf");
Response.TransmitFile(filePath);
Response.End();
}
In this example, clicking the button initiates a file download. The `Response.TransmitFile` method sends the file to the user’s browser, prompting them to download it.
Key Methods for File Download
- ContentType: Specifies the type of the file being downloaded (e.g., "application/pdf" for PDF files).
- AppendHeader: Adds headers like "Content-Disposition" to indicate attachment download.
- TransmitFile: Sends the file to the client.
ASP.NET Cookie
In ASP.NET, a Cookie is a small piece of data stored on the user's computer by the web browser. Cookies are used to store user information for future requests or to track user behavior across pages.
Creating a Cookie
// Creating a Cookie in ASP.NET (C#)
HttpCookie userCookie = new HttpCookie("UserInfo");
userCookie["Username"] = "JohnDoe";
userCookie["Preferences"] = "DarkMode";
userCookie.Expires = DateTime.Now.AddDays(7);
Response.Cookies.Add(userCookie);
Reading a Cookie
// Reading a Cookie in ASP.NET (C#)
HttpCookie userCookie = Request.Cookies["UserInfo"];
if (userCookie != null)
{
string username = userCookie["Username"];
string preferences = userCookie["Preferences"];
}
Key Properties of Cookie
- Expires: Sets the expiration date of the cookie.
- HttpOnly: Makes the cookie inaccessible via client-side scripts for security.
- Secure: Sends the cookie only over HTTPS connections.
ASP.NET Session
An ASP.NET Session is used to store data for a user across multiple HTTP requests. It is server-side and typically used to preserve user-specific data like authentication information.
Creating a Session
// Creating a Session in ASP.NET (C#) Session["Username"] = "JohnDoe"; Session["IsLoggedIn"] = true;
Reading a Session
// Reading a Session in ASP.NET (C#)
if (Session["Username"] != null)
{
string username = Session["Username"].ToString();
bool isLoggedIn = (bool)Session["IsLoggedIn"];
}
Key Properties of Session
- Timeout: Defines the time in minutes before a session expires.
- SessionID: A unique identifier for the user's session.
- Abandon: Ends the current session.
ASP.NET DropDownList
The DropDownList control in ASP.NET is a dropdown menu that allows users to select one item from a list of options. It is often used for selecting categories, options, or other input selections.
DropDownList Example
< asp:DropDownList ID="ddlColors" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="ddlColors_SelectedIndexChanged">
< asp:ListItem Value="1">Red< /asp:ListItem>
< asp:ListItem Value="2">Green< /asp:ListItem>
< asp:ListItem Value="3">Blue< /asp:ListItem>
< /asp:DropDownList>
Code-Behind for DropDownList (C#)
// Code-behind for DropDownList SelectedIndexChanged Event
protected void ddlColors_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedColor = ddlColors.SelectedItem.Text;
lblMessage.Text = "You selected: " + selectedColor;
}
Key Properties of DropDownList
- Items: Represents the list of items in the dropdown.
- SelectedIndex: Indicates the index of the selected item.
- AutoPostBack: Triggers a postback when the selection changes.
ASP.NET DataList
The DataList control in ASP.NET is used to display a collection of data in a flexible, repeatable layout. It is ideal for showing data in a tabular or formatted style with custom item templates.
DataList Example
< asp:DataList ID="dataListProducts" runat="server"
DataSourceID="sqlDataSource">
< ItemTemplate>
< div>
< strong>Product:< /strong> <%# Eval("ProductName") %>
< br />
< strong>Price: <%# Eval("Price") %>
< /div>
< /ItemTemplate>
< /asp:DataList>
< asp:SqlDataSource ID="sqlDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:YourConnectionString %>"
SelectCommand="SELECT ProductName, Price FROM Products">< /asp:SqlDataSource>
Key Features of DataList
- ItemTemplate: Defines how each item in the DataList is displayed.
- DataSource: Specifies the data source for the DataList.
- RepeatColumns: Defines the number of columns to display.
ASP.NET DataGrid
The DataGrid control in ASP.NET Web Forms is used to display tabular data in a grid format. It offers features like sorting, paging, and editing data, making it very powerful for displaying large datasets.
Basic DataGrid Example
< asp:DataGrid ID="dataGrid1" runat="server" AutoGenerateColumns="False"
DataKeyField="ProductID" OnItemCommand="dataGrid1_ItemCommand">
< Columns>
< asp:BoundColumn HeaderText="Product Name" DataField="ProductName" SortExpression="ProductName" />
< asp:BoundColumn HeaderText="Price" DataField="Price" SortExpression="Price" />
< asp:ButtonColumn HeaderText="Details" ButtonType="Link" CommandName="Details" Text="View Details" />
< /Columns>
< /asp:DataGrid>
Code-Behind for DataGrid (C#)
// Handling item commands in DataGrid
protected void dataGrid1_ItemCommand(object source, DataGridCommandEventArgs e)
{
if (e.CommandName == "Details")
{
string productID = dataGrid1.DataKeys[e.Item.ItemIndex].ToString();
Response.Redirect("ProductDetails.aspx?ProductID=" + productID);
}
}
Key Features of DataGrid
- AutoGenerateColumns: Automatically generates columns for each field in the data source.
- BoundColumn: Used to bind data from the source to the grid.
- ButtonColumn: Provides buttons that perform actions like editing, deleting, or navigating.
- Sorting: Allows sorting the columns by clicking on the header.
ASP.NET Web Forms User Registration
User registration in ASP.NET Web Forms can be accomplished using the TextBox controls for input and the Button control for submission. Validation controls like RequiredFieldValidator can be used to ensure data is provided.
User Registration Form Example
< form id="form1" runat="server">
< asp:TextBox ID="txtUsername" runat="server" placeholder="Enter Username">< /asp:TextBox>
< asp:RequiredFieldValidator ID="rfvUsername" runat="server" ControlToValidate="txtUsername"
ErrorMessage="Username is required" ForeColor="Red" />
< asp:TextBox ID="txtPassword" runat="server" placeholder="Enter Password" TextMode="Password">< /asp:TextBox>
< asp:RequiredFieldValidator ID="rfvPassword" runat="server" ControlToValidate="txtPassword"
ErrorMessage="Password is required" ForeColor="Red" />
< asp:Button ID="btnRegister" runat="server" Text="Register" OnClick="btnRegister_Click" />
< /form>
Code-Behind for User Registration (C#)
// Handling registration in code-behind
protected void btnRegister_Click(object sender, EventArgs e)
{
string username = txtUsername.Text;
string password = txtPassword.Text;
// Here, you would typically insert the user's data into a database
// Example: Registration logic, like checking if the username already exists.
Response.Redirect("Welcome.aspx");
}
Key Features of User Registration
- RequiredFieldValidator: Ensures the user fills in all necessary fields.
- TextMode="Password": Used to hide the text entered for sensitive fields like passwords.
- Redirecting after registration: Typically, you redirect the user to a welcome page or dashboard.
ASP.NET Web Forms Event Handling
Event handling in ASP.NET Web Forms is typically managed via the event handlers in the code-behind file. You can handle events like button clicks, form submission, and other user interactions.
Button Click Event Example
< asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
Code-Behind for Event Handling (C#)
// Handling button click event
protected void btnSubmit_Click(object sender, EventArgs e)
{
lblMessage.Text = "Button clicked!";
}
Event Handling in ASP.NET
- OnClick: An event handler is triggered when the button is clicked.
- Event Handlers: Each event corresponds to a method in the code-behind that executes when the event is triggered (e.g., button click, form submit).
ASP.NET Web Forms Authentication
ASP.NET Web Forms provides built-in authentication mechanisms, including forms authentication. This allows you to restrict access to pages and require users to log in.
Forms Authentication Example
< configuration>
< system.web>
< authentication mode="Forms">
< forms loginUrl="Login.aspx" timeout="30" />
< /authentication>
< /system.web>
< /configuration>
Login Form Example
< asp:TextBox ID="txtUsername" runat="server" placeholder="Username">< /asp:TextBox> < asp:TextBox ID="txtPassword" runat="server" TextMode="Password" placeholder="Password">< /asp:TextBox> < asp:Button ID="btnLogin" runat="server" Text="Login" OnClick="btnLogin_Click" />
Code-Behind for Forms Authentication (C#)
// Handling login logic in code-behind
protected void btnLogin_Click(object sender, EventArgs e)
{
string username = txtUsername.Text;
string password = txtPassword.Text;
// Validate credentials (typically check against a database)
if (username == "admin" && password == "password")
{
FormsAuthentication.RedirectFromLoginPage(username, false);
}
else
{
lblMessage.Text = "Invalid credentials!";
}
}
Key Features of Authentication
- FormsAuthentication: Manages user authentication and redirects users to a protected page after logging in.
- loginUrl: Specifies the URL to redirect users to for login if they are not authenticated.
- RedirectFromLoginPage: Used to redirect authenticated users to the originally requested page.
ASP.NET HTML Server Controls
In ASP.NET Web Forms, you can use standard HTML elements as server-side controls by adding the runat="server" attribute. This allows you to interact with these controls in the code-behind, making them behave like server controls.
Example of HTML Server Control
< input type="text" id="txtUsername" runat="server" /> < button id="btnSubmit" runat="server" onclick="btnSubmit_Click">Submit< /button>
Code-Behind for HTML Server Control (C#)
// Code-behind for HTML Server Control
protected void btnSubmit_Click(object sender, EventArgs e)
{
string username = txtUsername.Value; // Access the input value
Response.Write("Hello, " + username);
}
In this example, an < input> element and a < button> are both made server-side by adding the `runat="server"` attribute. The button click event is handled in the code-behind, where the username entered in the input field is retrieved and displayed.
ASP.NET Validation Controls
ASP.NET provides several validation controls that can be used to ensure the user inputs are valid before processing data on the server. These validation controls are easy to implement and can be customized to suit various needs.
Common ASP.NET Validation Controls
The following are some commonly used validation controls:
- CompareValidator: Compares the value of a control to another control or a fixed value.
- RangeValidator: Ensures that a value falls within a specified range of numbers or dates.
- RegularExpressionValidator: Validates input using a regular expression.
ASP.NET CompareValidator
The CompareValidator control is used to compare the value entered by the user in one input control with another control's value or a fixed value. It can be useful for confirming values like email addresses, passwords, or checking if one field is greater than another.
Basic CompareValidator Example
< asp:TextBox ID="txtPassword" runat="server" TextMode="Password" placeholder="Enter Password" />
< asp:TextBox ID="txtConfirmPassword" runat="server" TextMode="Password" placeholder="Confirm Password" />
< asp:CompareValidator
ID="cvPassword"
runat="server"
ControlToCompare="txtPassword"
ControlToValidate="txtConfirmPassword"
ErrorMessage="Passwords do not match!"
ForeColor="Red" />
Code-Behind for CompareValidator (C#)
// No code-behind required for CompareValidator as it works on the client side by default
In this example, the CompareValidator ensures that the password entered in the txtPassword field matches the value in the txtConfirmPassword field.
ASP.NET RangeValidator
The RangeValidator control is used to check whether the value entered by the user is within a specific range. This can be used to validate numeric values, dates, or strings.
Basic RangeValidator Example
< asp:TextBox ID="txtAge" runat="server" placeholder="Enter Age" />
< asp:RangeValidator
ID="rvAge"
runat="server"
ControlToValidate="txtAge"
MinimumValue="18"
MaximumValue="100"
Type="Integer"
ErrorMessage="Age must be between 18 and 100"
ForeColor="Red" />
Code-Behind for RangeValidator (C#)
// No code-behind required for RangeValidator as it works on the client side by default
In this example, the RangeValidator ensures that the user enters an age between 18 and 100. The Type="Integer" specifies that the validation is for numeric values.
ASP.NET RegularExpressionValidator
The RegularExpressionValidator control is used to validate user input using a regular expression. This can be very useful for validating complex patterns such as email addresses, phone numbers, or custom patterns.
Basic RegularExpressionValidator Example
< asp:TextBox ID="txtEmail" runat="server" placeholder="Enter Email" />
< asp:RegularExpressionValidator
ID="revEmail"
runat="server"
ControlToValidate="txtEmail"
ValidationExpression="^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
ErrorMessage="Please enter a valid email address"
ForeColor="Red" />
Code-Behind for RegularExpressionValidator (C#)
// No code-behind required for RegularExpressionValidator as it works on the client side by default
In this example, the RegularExpressionValidator ensures that the input is a valid email address based on the provided regular expression.
ASP.NET RequiredFieldValidator
The RequiredFieldValidator control is used to ensure that a field is not left empty. It is typically used for mandatory fields such as name, email, or password. If the user tries to submit the form without filling in a required field, the control will display an error message.
Basic RequiredFieldValidator Example
< asp:TextBox ID="txtName" runat="server" placeholder="Enter Your Name" />
< asp:RequiredFieldValidator
ID="rfvName"
runat="server"
ControlToValidate="txtName"
ErrorMessage="Name is required!"
ForeColor="Red" />
Code-Behind for RequiredFieldValidator (C#)
// No code-behind required for RequiredFieldValidator as it works on the client side by default
In this example, the RequiredFieldValidator ensures that the user does not leave the txtName field empty. If the field is left blank, the error message will be displayed.
ASP.NET ValidationSummary
The ValidationSummary control is used to display all validation error messages in a summary format, typically at the top or bottom of a form. This helps users easily see which fields need to be corrected. It can also be customized to display a list of all validation errors or just the first error.
Basic ValidationSummary Example
< asp:TextBox ID="txtName" runat="server" placeholder="Enter Your Name" />
< asp:RequiredFieldValidator
ID="rfvName"
runat="server"
ControlToValidate="txtName"
ErrorMessage="Name is required!"
ForeColor="Red" />
< asp:ValidationSummary
ID="vsSummary"
runat="server"
HeaderText="Please fix the following errors:"
ForeColor="Red"
ShowSummary="True"
ShowMessageBox="False" />
Code-Behind for ValidationSummary (C#)
// No code-behind required for ValidationSummary as it works on the client side by default
In this example, the ValidationSummary will display a list of validation errors. If the txtName field is left empty, the summary will show the error message "Name is required!".
ASP.NET MVC Project
ASP.NET MVC (Model-View-Controller) is a design pattern that separates the application into three main components:
- Model: Represents the application’s data and business logic.
- View: Represents the UI components, displaying the data provided by the model.
- Controller: Handles user input, updates the model, and returns a view to the user.
Create a Simple MVC Project in Visual Studio
// 1. Open Visual Studio // 2. Click 'File' > 'New' > 'Project' // 3. Select 'ASP.NET Core Web App (Model-View-Controller)' // 4. Choose a project name and click 'Create'
ASP.NET MVC Controller
In ASP.NET MVC, controllers are classes that handle HTTP requests, process user input, and return a response. They are typically placed in the Controllers folder of the project. A controller inherits from the Controller class.
Basic Controller Example
// Controller Class Example
public class HomeController : Controller
{
public IActionResult Index()
{
// Return a view called "Index"
return View();
}
public IActionResult About()
{
// Return a view called "About"
return View();
}
}
In this example, the HomeController defines two actions: Index and About. These actions are methods that return views when called.
ASP.NET MVC Actions
An Action in ASP.NET MVC is a method inside a controller that handles a request. When a user accesses a specific URL, an action method is called. The action can return a View, JSON data, Redirect to another action, or perform other responses.
Action Method Example
// Action method returning a view
public IActionResult Contact()
{
return View();
}
The above example shows a simple action method called Contact that returns a view named "Contact" when invoked.
ASP.NET MVC Action Selectors
Action selectors in ASP.NET MVC allow you to specify how an action method should respond to different HTTP request methods (e.g., GET, POST). You can use attributes such as [HttpGet], [HttpPost], and [ActionName] to define behavior.
Action Selectors Example
// Action with GET method
[HttpGet]
public IActionResult Register()
{
return View();
}
// Action with POST method
[HttpPost]
public IActionResult Register(User user)
{
if (ModelState.IsValid)
{
// Process the registration
return RedirectToAction("Index");
}
return View(user);
}
In the example above, the Register action method uses both the [HttpGet] and [HttpPost] attributes to distinguish between the GET and POST requests. When the user first visits the page, the GET version is called, and when they submit the form, the POST version is invoked.
MVC Action Filters
In ASP.NET MVC, Action Filters allow you to run code before or after an action executes. They are often used for logging, performance measurement, validation, or authorization. Action filters can be applied globally, on specific controllers, or on individual action methods.
Example of Action Filter
// Custom Action Filter Example
public class LogActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
// Log action execution
Console.WriteLine("Action Executing...");
}
public override void OnActionExecuted(ActionExecutedContext context)
{
// Log after action execution
Console.WriteLine("Action Executed...");
}
}
// Applying Filter to Controller
[LogActionFilter]
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}
In this example, a custom action filter LogActionFilter logs messages before and after the execution of actions in the controller.
MVC Model
The Model in ASP.NET MVC represents the application's data and business logic. It is responsible for retrieving, storing, and processing data from a database or other data sources. The model is usually composed of classes that represent data entities and may contain logic to validate or manipulate that data.
Example of MVC Model
// MVC Model Example
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
Here, the User class represents a data entity with properties like Id, Name, and Email. The model is used to store and pass data between the controller and the view.
MVC Model Binding
Model Binding in ASP.NET MVC is the process of mapping data from the request (typically from form inputs or URL parameters) to a model object. The framework automatically binds the incoming request data to the properties of a model.
Example of Model Binding
// Controller Action with Model Binding
[HttpPost]
public IActionResult Register(User user)
{
if (ModelState.IsValid)
{
// Use the model data
// Save to database or perform other logic
return RedirectToAction("Index");
}
return View(user);
}
In the example, the Register action method accepts a User object, which is automatically populated with data from the incoming HTTP request (form submission). The properties of the User model are bound to the corresponding form fields by the MVC framework.
MVC View
The View in ASP.NET MVC is responsible for rendering the user interface. It displays the data passed from the controller in a specific format, such as HTML, and allows the user to interact with the application. Views are typically composed of Razor syntax, a lightweight templating engine that integrates C# code with HTML.
Example of MVC View
// View (Razor) Example - Register.cshtml
@model User
< form method="post">
< div>
< label for="Name">Name:< /label>
< input type="text" id="Name" name="Name" value="@Model.Name" />
< /div>
< div>
< label for="Email">Email:< /label>
< input type="text" id="Email" name="Email" value="@Model.Email" />
< /div>
< div>
< button type="submit">Register< /button>
< /div>
< /form>
This Razor view corresponds to the Register action. It generates a form where users can input their name and email. The form data will be sent as a POST request, and the model is bound to the view.
MVC Validation
Validation is an essential part of any web application, ensuring that user inputs are correct and meet predefined criteria before being processed. ASP.NET MVC provides robust ways to validate user input using data annotations and custom validation logic.
Example of Validation using Data Annotations
// Model with Validation Annotations
public class User
{
[Required(ErrorMessage = "Name is required.")]
[StringLength(50, MinimumLength = 5, ErrorMessage = "Name must be between 5 and 50 characters.")]
public string Name { get; set; }
[Required(ErrorMessage = "Email is required.")]
[EmailAddress(ErrorMessage = "Invalid email address.")]
public string Email { get; set; }
}
Here, the User model uses data annotations like [Required] and [EmailAddress] to enforce validation rules. If the user fails to provide valid data, appropriate error messages will be shown.
Using Validation in View
// View Example (Razor) - Register.cshtml
@model User
< form method="post">
< div>
< label for="Name">Name:< /label>
< input type="text" id="Name" name="Name" value="@Model.Name" />
@Html.ValidationMessageFor(model => model.Name)
< /div>
< div>
< label for="Email">Email:< /label>
< input type="text" id="Email" name="Email" value="@Model.Email" />
@Html.ValidationMessageFor(model => model.Email)
< /div>
< button type="submit">Register< /button>
< /form>
In the view, @Html.ValidationMessageFor is used to display validation error messages when the input does not meet the defined criteria.
MVC Entity Framework
Entity Framework (EF) is an Object-Relational Mapping (ORM) framework that allows developers to interact with a database using objects. In MVC applications, EF simplifies database operations such as querying, inserting, updating, and deleting data without needing to write raw SQL.
Example of Using Entity Framework
// Defining a Model - User.cs
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
// DbContext - ApplicationDbContext.cs
public class ApplicationDbContext : DbContext
{
public DbSet Users { get; set; }
}
// Controller - HomeController.cs
public class HomeController : Controller
{
private readonly ApplicationDbContext _context;
public HomeController(ApplicationDbContext context)
{
_context = context;
}
// Index Action - Display Users
public IActionResult Index()
{
var users = _context.Users.ToList();
return View(users);
}
// Create Action - Add New User
[HttpPost]
public IActionResult Create(User user)
{
if (ModelState.IsValid)
{
_context.Users.Add(user);
_context.SaveChanges();
return RedirectToAction("Index");
}
return View(user);
}
}
In this example, Entity Framework is used to interact with the database. The ApplicationDbContext class inherits from DbContext and provides a DbSet{`
MVC Authentication
Authentication in ASP.NET MVC ensures that only authorized users can access certain parts of an application. This is typically done by verifying user credentials, such as username and password, before granting access to resources.
Example of Authentication
// Controller - AccountController.cs
public class AccountController : Controller
{
// Login Action
[HttpGet]
public IActionResult Login()
{
return View();
}
[HttpPost]
public IActionResult Login(string username, string password)
{
if (username == "admin" && password == "password")
{
// Set session or cookie for authentication
HttpContext.Session.SetString("User", username);
return RedirectToAction("Dashboard");
}
ModelState.AddModelError(string.Empty, "Invalid credentials.");
return View();
}
// Dashboard Action
public IActionResult Dashboard()
{
// Check if user is authenticated
if (HttpContext.Session.GetString("User") == null)
{
return RedirectToAction("Login");
}
return View();
}
}
In this example, the Login action handles both the GET and POST requests. If the credentials are correct, the user's session is set, allowing them to access the Dashboard page. If authentication fails, the user is prompted with an error message.
MVC Bootstrap
Bootstrap is a front-end framework for designing responsive web applications. It provides pre-built CSS and JavaScript components like navigation bars, forms, buttons, and modals. You can easily integrate Bootstrap into your ASP.NET MVC views to enhance the user interface.
Example of Using Bootstrap in MVC View
// View Example (Razor) - Register.cshtml
@model User
@{
ViewData["Title"] = "Register";
}
< div class="container">
< h2>@ViewData["Title"]< /h2>
< form method="post">
< div class="form-group">
< label for="Name">Name:< /label>
< input type="text" class="form-control" id="Name" name="Name" value="@Model.Name" />
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
< /div>
< div class="form-group">
< label for="Email">Email:< /label>
< input type="text" class="form-control" id="Email" name="Email" value="@Model.Email" />
@Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
< /div>
< button type="submit" class="btn btn-primary">Register< /button>
< /form>
< /div>
This example demonstrates how to use Bootstrap for styling a registration form. The form-control class applies Bootstrap's styling to the input fields, and the btn btn-primary class styles the submit button.
MVC Routing
Routing in ASP.NET MVC is responsible for mapping incoming URLs to specific controller actions. The routing system uses a pattern-matching approach to determine which controller and action to invoke based on the URL.
Default Routing
// RouteConfig.cs (App_Start folder)
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// Default route
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
The RegisterRoutes method in the RouteConfig class defines the URL pattern for the MVC application. In this example, the URL pattern is /{controller}/{action}/{id}, where:
- controller: The name of the controller.
- action: The name of the action method to invoke.
- id: An optional parameter.
Custom Routing
// Custom route example
routes.MapRoute(
name: "CustomRoute",
url: "Products/{category}/{id}",
defaults: new { controller = "Products", action = "Details", id = UrlParameter.Optional }
);
Custom routes can be defined to match specific URL patterns. In the above example, the route is designed to handle URLs like /Products/Electronics/1, where category is the first parameter, and id is the second.
MVC Scaffolding
Scaffolding in ASP.NET MVC is a code generation technique used to quickly generate CRUD (Create, Read, Update, Delete) operations for models. Scaffolding automatically generates controller actions, views, and the necessary model logic.
Scaffolding Example
// Step 1: Create a Model (e.g., Product.cs)
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
// Step 2: Scaffold a Controller with Views
// Right-click the Controllers folder in Visual Studio > Add > Controller
// Select 'MVC 5 Controller with views, using Entity Framework'
// The scaffolding will generate the controller and views with CRUD operations for Product
Scaffolding automatically creates the necessary code for CRUD operations. For instance, after generating the scaffolded controller, you'll get actions like Create, Edit, Delete, and Details in your controller, along with corresponding Razor views for each action.
Benefits of Scaffolding
- Speeds up development by automatically generating CRUD operations.
- Helps developers adhere to best practices by generating organized, clean code.
- Allows developers to focus on business logic and UI customization rather than writing repetitive CRUD code.
MVC ViewBag
ViewBag is a dynamic object used to pass data from the controller to the view in ASP.NET MVC. It allows you to store data temporarily and access it in your Razor views.
Using ViewBag to Pass Data
// Controller - HomeController.cs
public class HomeController : Controller
{
public IActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();
}
}
// View - Index.cshtml
< h2>@ViewBag.Message< /h2>
In this example, the ViewBag.Message is set in the controller and displayed in the Razor view. The ViewBag is useful for passing simple data like strings, numbers, and collections from the controller to the view.
Using ViewBag for Complex Data
// Controller - HomeController.cs
public IActionResult About()
{
var model = new { Name = "John Doe", Age = 30 };
ViewBag.User = model;
return View();
}
// View - About.cshtml
< p>Name: @ViewBag.User.Name < /p>
< p>Age: @ViewBag.User.Age< /p>
You can also use ViewBag to pass complex data types like anonymous objects. In the example above, a user object with properties Name and Age is passed from the controller to the view and displayed.
Limitations of ViewBag
Although ViewBag is useful for small data transfer between controller and view, it is not strongly typed. This means there is no compile-time checking for data, which can lead to runtime errors if you reference properties that don’t exist or are incorrect.
For complex data transfer between controller and view, it's often better to use ViewModel instead of ViewBag, as it provides stronger typing and better performance.
ASP.NET Razor
Razor Code Expressions
Razor syntax allows you to write C# code directly within your HTML markup. Razor code expressions are used to evaluate C# expressions and output them into the page. Code expressions are wrapped in @ symbols.
Basic Razor Expression
< h2>@DateTime.Now< /h2>
This example outputs the current date and time on the webpage using Razor's code expression. The expression @DateTime.Now is evaluated, and the result is rendered into the HTML.
Razor Code Blocks
Razor code blocks are used to write more complex C# logic and can contain multiple statements. Code blocks are enclosed in @{} and are useful for performing operations like looping, conditionals, etc.
Example: Razor Code Block
@{
var message = "Hello, Razor!";
var currentYear = DateTime.Now.Year;
}
< p>@message< /p>
< p>Current Year: @currentYear< /p>
In this example, the message and currentYear variables are defined in the Razor code block and then displayed in the HTML output using @ syntax.
Razor Control Structures
Razor also supports control structures like if-else, for, and foreach. These structures allow you to control the flow of your application logic directly within Razor views.
Example: Razor If-Else
@{
var isLoggedIn = true;
}
< p>@if (isLoggedIn) {
< text>Welcome back!< /text>
} else {
< text>Please log in.< /text>
}< /p>
This example demonstrates an if-else control structure in Razor. The output depends on the value of the isLoggedIn variable.
Example: Razor For-Each Loop
@{
var fruits = new List< string> { "Apple", "Banana", "Cherry" };
}
< ul>
@foreach (var fruit in fruits)
{
< li>@fruit< /li>
}
< /ul>
The foreach loop iterates through the fruits list, generating a list of <li> items in HTML.
Razor HTML Helpers
Razor HTML helpers are methods used to generate HTML elements. These helpers can be used to create form elements, links, and other HTML elements with ease, and they allow you to inject values dynamically from your model.
Example: HTML Helper for Form
@using (Html.BeginForm())
{
< label for="name">Name:< /label>
@Html.TextBoxFor(model => model.Name)
< button type="submit">Submit< /button>
}
The TextBoxFor helper generates an HTML <input> element bound to the Name property of the model. The BeginForm helper starts a form that will post to the current controller action.
Example: HTML Helper for DropDownList
@Html.DropDownListFor(model => model.Country, new SelectList(Model.Countries))
The DropDownListFor helper generates a <select> dropdown, and the SelectList is used to populate the list with country options dynamically from the model.
Razor Partial Views
Partial views are used to render reusable components or sections of content within a view. These views are not standalone and must be invoked from a parent view.
Example: Rendering a Partial View
// Parent View (Index.cshtml)
@{ Html.RenderPartial("_ProductList", Model.Products); }
In the above example, the RenderPartial method is used to include the content from the _ProductList.cshtml partial view into the parent view.
Example: Passing Data to Partial View
// Parent View (Index.cshtml)
@{ Html.RenderPartial("_ProductList", new ProductListViewModel { Products = Model.Products }); }
You can also pass a model to a partial view. In this case, the _ProductList partial view receives a ProductListViewModel that contains a list of products.