Learining
Learining
NET
#asp.net
Table of Contents
About 1
Remarks 2
Examples 2
Installation or Setup 2
ASP.NET Overview 2
Examples 5
Getting Started 5
Syntax 7
Examples 7
List Controls 9
HyperLink Control 11
Image Control 11
Examples 13
View State 13
Introduction 15
Examples 15
Syntax 18
Examples 18
Validation controls 18
RequiredFieldValidator Control 18
RangeValidator Control 19
CompareValidator Control 19
RegularExpressionValidator 20
Validation Summary 21
Validation Groups 22
Examples 25
Examples 27
Data Cache 27
Examples 29
Retrieving Data 29
Basic Usage 30
Syntax 32
Examples 32
Parameters 34
Remarks 34
Examples 34
Basic Info 34
Declaration 34
Chapter 12: Directives 36
Examples 36
Syntax 40
Remarks 40
Examples 40
Syntax 43
Parameters 43
Examples 43
Default Events 44
Examples 47
Evaluated Expression 47
Syntax 48
Remarks 48
Examples 48
Examples 49
Data Binding 49
Manual Binding 49
DataSourceControl 49
Columns 49
Paging 52
ObjectDataSource 52
Manual Binding 53
Examples 57
Introduction 59
Examples 59
Example 59
Parameters 61
Remarks 61
Examples 61
Examples 63
Code Example 64
Parameters 68
Remarks 68
Return value 68
Examples 68
How to call it 68
Examples 70
Basic usage 70
Introduction 71
Syntax 71
Examples 71
Examples 73
Syntax 74
Remarks 74
Examples 74
Introduction 77
Syntax 77
Remarks 77
Examples 77
Introduction 79
Syntax 79
Examples 79
Example 79
Introduction 81
Examples 81
Syntax 82
Remarks 82
Examples 82
Grouping in ListView 83
Example 85
Hyperlink 85
Introduction 87
Remarks 87
Examples 87
Calculator WebService 87
Credits 89
About
You can share this PDF with anyone you feel could benefit from it, downloaded the latest version
from: asp-net
It is an unofficial and free ASP.NET ebook created for educational purposes. All the content is
extracted from Stack Overflow Documentation, which is written by many hardworking individuals at
Stack Overflow. It is neither affiliated with Stack Overflow nor official ASP.NET.
The content is released under Creative Commons BY-SA, and the list of contributors to each
chapter are provided in the credits section at the end of this book. Images may be copyright of
their respective owners unless otherwise specified. All trademarks and registered trademarks are
the property of their respective company owners.
Use the content presented in this book at your own risk; it is not guaranteed to be correct nor
accurate, please send your feedback and corrections to [email protected]
https://riptutorial.com/ 1
Chapter 1: Getting started with ASP.NET
Remarks
ASP.NET is a collection of technologies within the .NET Framework that are targeted towards web
application development. These technologies consist of:
Examples
Installation or Setup
By default, all the required libraries for build ASP.NET applications are included during the
installation of Visual Studio. If a newer version of ASP.NET is released that was not included with
Visual Studio, you can download the appropriate SDK library from Microsoft, which will include all
the necessary libraries for that version.
Similarly, the Windows operating system comes pre-installed with a more recent version of
ASP.NET and is automatically registered with IIS for configuration and execution. Similarly, if a
newer version of ASP.NET becomes available, you can install the SDK for the version you need
and then use the aspnet_regiis tool to register the framework with IIS for use.
It should be also noted that for server deployments, there also exists a ASP.NET SDK
Redistributable package. This version is a streamlined version of the SDK, with just the essential
libraries and does not have the tools and integrations with Visual Studio in it.
ASP.NET Overview
ASP.NET is a unified Web development model that includes the services necessary for you to
build enterprise-class Web applications with a minimum of coding. ASP.NET is part of the .NET
Framework, and when coding ASP.NET applications you have access to classes in the .NET
Framework.
You can code your applications in any language compatible with the common language runtime
(CLR), including Microsoft Visual Basic, C#, JScript .NET, and J#. These languages enable you to
develop ASP.NET applications that benefit from the common language runtime, type safety,
inheritance, and so on.
ASP.NET includes:
https://riptutorial.com/ 2
• The ASP.NET compiler
• Security infrastructure
• State-management facilities
• Application configuration
• Health monitoring and performance features
• Debugging support
• An XML Web services framework
• Extensible hosting environment and application life cycle management
• An extensible designer environment
install-packet Microsoft.Owin.SelfHost
Code for a bare minimum HelloWorld web application running from a console window:
namespace HelloOwin
{
using System;
using Owin;
class Program
{
static readonly string baseUrl = "http://localhost:8080";
Asp.net is web application framework developed by Microsoft to build dynamic data-driven Web
https://riptutorial.com/ 3
Application and WebServices.
Asp.net is basically a subset of wider .NET framework. A framework is nothing but a collection of
classes.
In .NET Framework you can build Console application. Web Application, Window Application,
Mobile Application. So for web application ASP.net is being used.
A web application is an application that is accessed by users using a web browser such as:
https://riptutorial.com/ 4
Chapter 2: Asp Web Forms Identity
Examples
Getting Started
Getting Started
1. Microsoft.AspNet.Identity.EntityFramework
2. Microsoft.AspNet.Identity.Core
3. Microsoft.AspNet.Identity.OWIN
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser() { UserName = model.UserName };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", "Home");
}
else
{
AddErrors(result);
}
}
AuthenticationManager.SignIn(
new AuthenticationProperties() {
https://riptutorial.com/ 5
IsPersistent = isPersistent
}, identity);
}
Log off
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
AuthenticationManager.SignOut();
return RedirectToAction("Index", "Home");
}
https://riptutorial.com/ 6
Chapter 3: ASP.NET - Basic Controls
Syntax
• <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Click" / >
<asp:TextBox ID="txtstate" runat="server">
• </asp:TextBox> <asp:CheckBox ID= "chkoption" runat= "Server"> </asp:CheckBox>
<asp:RadioButton ID= "rdboption" runat= "Server"> </asp: RadioButton>
• <asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="ListBox1_SelectedIndexChanged"> </asp:ListBox>
• <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
• <asp:RadioButtonList ID="RadioButtonList1" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged">
</asp:RadioButtonList>
• <asp:CheckBoxList ID="CheckBoxList1" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="CheckBoxList1_SelectedIndexChanged"> </asp:CheckBoxList>
• <asp:BulletedList ID="BulletedList1" runat="server"> </asp:BulletedList>
• <asp:HyperLink ID="HyperLink1" runat="server"> HyperLink </asp:HyperLink> <asp:Image
ID="Image1" runat="server">
Examples
Text Boxes and Labels
Text box controls are typically used to accept input from the user. A text box control can accept
one or more lines of text depending upon the settings of the TextMode attribute.
Label controls provide an easy way to display text which can be changed from one execution of a
page to the next. If you want to display text that does not change, you use the literal text.
Properties Description
Specifies the type of text box. SingleLine creates a standard text box, MultiLIne
TextMode creates a text box that accepts more than one line of text and the Password
causes the characters that are entered to be masked. The default is SingleLine.
https://riptutorial.com/ 7
Properties Description
MaxLength The maximum number of characters that can be entered into the text box.
It determines whether or not text wraps automatically for multi-line text box;
Wrap
default is true.
Determines whether the user can change the text in the box; default is false,
ReadOnly
i.e., the user can change the text.
The width of the text box in characters. The actual width is determined based on
Columns
the font that is used for the text entry.
The height of a multi-line text box in lines. The default value is 0, means a
Rows
single line text box.
The mostly used attribute for a label control is 'Text', which implies the text displayed on the label.
A check box displays a single option that the user can either check or uncheck and radio buttons
present a group of options from which the user can select just one option.
To create a group of radio buttons, you specify the same name for the GroupName attribute of
each radio button in the group. If more than one group is required in a single form, then specify a
different group name for each group.
If you want check box or radio button to be selected when the form is initially displayed, set its
Checked attribute to true. If the Checked attribute is set to true for multiple radio buttons in a
group, then only the last one is considered as true.
Properties Description
Text The text displayed next to the check box or radio button.
https://riptutorial.com/ 8
List Controls
• Drop-down list
• List box
• Radio button list
• Check box list
• Bulleted list
These control let a user choose from one or more items from the list. List boxes and drop-down
lists contain one or more list items. These lists can be loaded either by code or by the
ListItemCollection editor.
Properties Description
The collection of ListItem objects that represents the items in the control.
Items
This property returns an object of type ListItemCollection.
Specifies the number of items displayed in the box. If actual list contains
Rows
more rows than displayed then a scroll bar is added.
The index of the currently selected item. If more than one item is selected,
SelectedIndex then the index of the first selected item. If no item is selected, the value of
this property is -1.
The value of the currently selected item. If more than one item is selected,
SelectedValue then the value of the first selected item. If no item is selected, the value of
this property is an empty string ("").
SelectionMode Indicates whether a list box allows single selections or multiple selections.
https://riptutorial.com/ 9
Properties Description
• To work with the items in a drop-down list or list box, you use the Items property of the
control. This property returns a ListItemCollection object which contains all the items of the
list.
• The SelectedIndexChanged event is raised when the user selects a different item from a
drop-down list or list box.
A radio button list presents a list of mutually exclusive options. A check box list presents a list of
independent options. These controls contain a collection of ListItem objects that could be referred
to through the Items property of the control.
Properties Description
This attribute specifies whether the table tags or the normal html flow to
RepeatLayout
use while formatting the list when it is rendered. The default is Table.
https://riptutorial.com/ 10
The bulleted list control creates bulleted lists or numbered lists. These controls contain a collection
of ListItem objects that could be referred to through the Items property of the control.
Properties Description
BulletStyle This property specifies the style and looks of the bullets, or numbers.
HyperLink Control
Properties Description
Image Control
The image control is used for displaying images on the web page, or some alternative text, if the
image is not available.
https://riptutorial.com/ 11
<asp:Image ID="Image1" runat="server">
Properties Description
https://riptutorial.com/ 12
Chapter 4: ASP.NET - Managing State
Examples
View State
The following example demonstrates the concept of storing view state. Let us keep a counter,
which is incremented each time the page is posted back by clicking a button on the page. A label
control shows the value in the counter.
<head runat="server">
<title>
Untitled Page
</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h3>View State demo</h3>
Page Counter:
</form>
</body>
</html>
https://riptutorial.com/ 13
return ((int)ViewState["pcounter"]);
}
else
{
return 0;
}
}
set
{
ViewState["pcounter"] = value;
}
}
https://riptutorial.com/ 14
Chapter 5: ASP.NET - User Controls
Introduction
User controls are containers which can be populated with HTML markup & server controls with
code-behind in the same way as ASPX page. They're treated as reusable smaller units of a page,
so they can't run as stand-alone pages and must not having html, body or form HTML elements
in them.
Examples
Introduction of User Controls
User controls are made for reusability across ASP.NET pages, similar to master pages. Instead of
sharing base page layout, user controls share group of HTML/ASP.NET built-in server controls or
a specific form layout, e.g. comment submission or guest notes.
A user control can contain both HTML controls and ASP.NET server controls, including client-side
scripts.
The user controls usually include Control directive on top of its definition:
Like ASPX page, user controls consists of markups which can be associated with a code behind
file to perform certain events and tasks, therefore all HTML tags available on ASPX page can be
used on user controls except <html>, <body> and <form> tags.
Code-behind example:
// UserControl.ascx.cs
public partial class UserControl : System.Web.UI.UserControl
{
protected void Button1_Click(Object sender, EventArgs e)
{
Label1.Text = "Hello World!";
}
}
https://riptutorial.com/ 15
Before a user control inserted in ASPX page, Register directive should declared on top of the page
referencing the user control with its source URL, tag name & tag prefix.
Afterwards, you can place user control inside ASPX page like ASP.NET built-in server control:
If you want to instantiate an instance of user control inside ASPX code behind page, you need to
write user control declaration on Page_Load event as follows:
Note that the user control ASCX file should be already created when executing LoadControl
method.
Depending on your need, PlaceHolder places user controls on a container storing all server
controls dynamically added into the page, where Page.Controls directly inserts user control inside
the page which more preferred for rendering HTML literal controls.
Like standard ASP.NET built-in server controls, user controls can have properties (attributes) on
its definition tag. Suppose you want to add color effect on UserControl.ascx file like this:
At this point, custom attributes/properties for user controls can be set by declaring properties
https://riptutorial.com/ 16
inside user control's code behind:
Additionally, if you want to set default value on a user control property, assign the default value
inside user control's constructor method.
public UserControl()
{
_color = "red";
}
Then, user control markup should be modified to add color attribute as following example:
https://riptutorial.com/ 17
Chapter 6: ASP.NET - Validators
Syntax
• RequiredFieldValidator Control: <asp:RequiredFieldValidator ID="rfvcandidate"
runat="server" ControlToValidate ="ddlcandidate" ErrorMessage="Please choose a
candidate" InitialValue="Please choose a candidate">
</asp:RequiredFieldValidator>
• RangeValidator Control:
• CustomValidator:
</asp:CustomValidator>
Examples
Validation controls
ASP.NET validation controls validate the user input data to ensure that useless, unauthenticated,
or contradictory data don't get stored.
• RequiredFieldValidator
• RangeValidator
• CompareValidator
• RegularExpressionValidator
• CustomValidator
• ValidationSummary
RequiredFieldValidator Control
https://riptutorial.com/ 18
The RequiredFieldValidator control ensures that the required field is not empty. It is generally tied
to a text box to force input into the text box.
<asp:RequiredFieldValidator ID="rfvcandidate"
runat="server" ControlToValidate ="ddlcandidate"
ErrorMessage="Please choose a candidate"
InitialValue="Please choose a candidate">
</asp:RequiredFieldValidator>
RangeValidator Control
The RangeValidator control verifies that the input value falls within a predetermined range.
Properties Description
Type It defines the type of the data. The available values are: Currency, Date,
</asp:RangeValidator>
CompareValidator Control
The CompareValidator control compares a value in one control with a fixed value or a value in
another control.
Properties Description
ValueToCompare It specifies the comparison operator, the available values are: Equal,
https://riptutorial.com/ 19
Properties Description
</asp:CompareValidator>
RegularExpressionValidator
The RegularExpressionValidator allows validating the input text by matching against a pattern of a
regular expression. The regular expression is set in the ValidationExpression property.
The following table summarizes the commonly used syntax constructs for regular expressions:
\b Matches a backspace.
\t Matches a tab.
\ Escape character.
Apart from single character match, a class of characters could be specified that can be matched,
called the metacharacters.
Metacharacters Description
https://riptutorial.com/ 20
Metacharacters Description
Quantifier Description
{N} N matches.
</asp:RegularExpressionValidator>
Validation Summary
The ValidationSummary control does not perform any validation but shows a summary of all errors
in the page. The summary displays the values of the ErrorMessage property of all validation
controls that failed validation.
The following two mutually inclusive properties list out the error message:
https://riptutorial.com/ 21
DisplayMode = "BulletList" ShowSummary = "true" HeaderText="Errors:" />
Validation Groups
Complex pages have different groups of information provided in different panels. In such situation,
a need might arise for performing validation separately for separate group. This kind of situation is
handled using validation groups.
To create a validation group, you should put the input controls and the validation controls into the
same logical group by setting their ValidationGroup property.
Example The following example describes a form to be filled up by all the students of a school,
divided into four houses, for electing the school president. Here, we use the validation controls to
validate the user input.
<tr>
<td class="style1" colspan="3" align="center">
<asp:Label ID="lblmsg"
Text="President Election Form : Choose your president"
runat="server" />
</td>
</tr>
<tr>
<td class="style3">
Candidate:
</td>
<td class="style2">
<asp:DropDownList ID="ddlcandidate" runat="server" style="width:239px">
<asp:ListItem>Please Choose a Candidate</asp:ListItem>
<asp:ListItem>M H Kabir</asp:ListItem>
<asp:ListItem>Steve Taylor</asp:ListItem>
https://riptutorial.com/ 22
<asp:ListItem>John Abraham</asp:ListItem>
<asp:ListItem>Venus Williams</asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:RequiredFieldValidator ID="rfvcandidate"
runat="server" ControlToValidate ="ddlcandidate"
ErrorMessage="Please choose a candidate"
InitialValue="Please choose a candidate">
</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="style3">
House:
</td>
<td class="style2">
<asp:RadioButtonList ID="rblhouse" runat="server" RepeatLayout="Flow">
<asp:ListItem>Red</asp:ListItem>
<asp:ListItem>Blue</asp:ListItem>
<asp:ListItem>Yellow</asp:ListItem>
<asp:ListItem>Green</asp:ListItem>
</asp:RadioButtonList>
</td>
<td>
<asp:RequiredFieldValidator ID="rfvhouse" runat="server"
ControlToValidate="rblhouse" ErrorMessage="Enter your house name" >
</asp:RequiredFieldValidator>
<br />
</td>
</tr>
<tr>
<td class="style3">
Class:
</td>
<td class="style2">
<asp:TextBox ID="txtclass" runat="server"></asp:TextBox>
</td>
<td>
<asp:RangeValidator ID="rvclass"
runat="server" ControlToValidate="txtclass"
ErrorMessage="Enter your class (6 - 12)" MaximumValue="12"
MinimumValue="6" Type="Integer">
</asp:RangeValidator>
</td>
</tr>
<tr>
<td class="style3">
Email:
</td>
<td class="style2">
<asp:TextBox ID="txtemail" runat="server" style="width:250px">
https://riptutorial.com/ 23
</asp:TextBox>
</td>
<td>
<asp:RegularExpressionValidator ID="remail" runat="server"
ControlToValidate="txtemail" ErrorMessage="Enter your email"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
</asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td class="style3" align="center" colspan="3">
<asp:Button ID="btnsubmit" runat="server" onclick="btnsubmit_Click"
style="text-align: center" Text="Submit" style="width:140px" />
</td>
</tr>
</table>
<asp:ValidationSummary ID="ValidationSummary1" runat="server"
DisplayMode ="BulletList" ShowSummary ="true" HeaderText="Errors:" />
</form>
https://riptutorial.com/ 24
Chapter 7: Asp.net Ajax Controls
Examples
FileUpload Ajax Toolkit Control
https://riptutorial.com/ 25
4. Make sure you have created folder named as Uploads in your project root directory.
https://riptutorial.com/ 26
Chapter 8: ASP.NET Caching
Examples
Data Cache
ASP.Net exposes Cache API to store data in the cache for retrieval later.
Getting Started
Store string
Cache["key"]="value";
Retrieve string
var value="";
if (Cache["key"] != null)
value = Cache["key"].ToString();
else
{
label1.Text + = "Item is accesses";
DateTime item = ( DateTime) Cache [ "item" ];
label1.Text + = "Time is: " + item.ToString();
label1.Text + = <br/>";
}
label1.Text + = "<br/>";
}
https://riptutorial.com/ 27
Read ASP.NET Caching online: https://riptutorial.com/asp-net/topic/9148/asp-net-caching
https://riptutorial.com/ 28
Chapter 9: Data Binding
Examples
SQL Data Source
Controls that can be bound with data can make use of SqlDataSource controls. The SqlDataSource
control not only allows you to retrieve data from a database, but also edit and sort the data.
Retrieving Data
Stored Procedure:
<asp:SqlDataSource ID="SqlDataSourceEmployees"
runat="server"
ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
SelectCommand="sp_GetEmployees"
SelectCommandType="StoredProcedure">
</asp:SqlDataSource>
SQL Query:
<asp:SqlDataSource ID="SqlDataSourceEmployees"
runat="server"
ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
SelectCommand="SELECT
EmployeeID,
EmployeeFirstName,
EmployeeLastName
FROM
dbo.Employees">
</asp:SqlDataSource>
Parameters:
<asp:SqlDataSource ID="SqlDataSourceEmployees"
runat="server"
ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
SelectCommand="SELECT
EmployeeID,
EmployeeFirstName,
EmployeeLastName
FROM
dbo.Employees
WHERE
DepartmentID = @DepartmentID;">
<SelectParameters>
<asp:ControlParameter ControlID="ddlDepartment"
Name="DepartmentID"
PropertyName="SelectedValue" />
</SelectParameters>
https://riptutorial.com/ 29
</asp:SqlDataSource>
Be aware of the CancelSelectOnNullParameter option, that if set to true (default) will stop the data
binding if any parameter is NULL
Basic Usage
GridView:
<asp:GridView ID="GridViewEmployees"
runat="server"
AutoGenerateColumns="false"
DataSourceID="SqlDataSourceEmployees">
<Columns>
<asp:BoundField DataField="EmployeeID" HeaderText="Employee ID" />
<asp:BoundField DataField="EmployeeFirstName" HeaderText="First Name" />
<asp:BoundField DataField="EmployeeLastName" HeaderText="Last Name" />
</Columns>
</asp:GridView>
return results;
}
https://riptutorial.com/ 30
public class Employee
{
public Int32EmployeeId { get; set; }
public string Name { get; set; }
}
https://riptutorial.com/ 31
Chapter 10: Data List
Syntax
1. ItemTemplate:It potrays the content and layout of items within the list.This is mandatory
Required
2. AlternatingItemTemplate:If mentioned, determines the content and layout of alternating
items. If not mentioned, ItemTemplate is used.
3. SeparatorTemplate : If mentioned, is rendered between items (and alternating items). If not
mentioned, a separator is not rendered.
4. SelectedItemTemplate : If mentioned, determines the content and layout of the selected
item. If not mentioned, ItemTemplate (AlternatingItemTemplate) is used.
5. EditItemTemplate :If mentioned, determines the content and layout of the item being edited.
If not mentioned, ItemTemplate (AlternatingItemTemplate, SelectedItemTemplate) is used.
6. HeaderTemplate:If mentioned, determines the content and layout of the list header. If not
mentioned, the header is not rendered.
7. FooterTemplate:If mentioned, determines the content and layout of the list footer. If not
mentioned, the footer is not rendered.
Examples
Data Binding in asp.net
Aspx
Aspx.cs
}
catch (Exception ex)
{
https://riptutorial.com/ 32
ErrorLogger.ClientErrorLogger(ex);
}
}
try
{
int BlogId = Convert.ToInt32(e.CommandArgument.ToString());
if (e.CommandName == "SampleName")
{
//your code
}
}
catch (Exception ex)
{
ErrorLogger.ClientErrorLogger(ex);
}
}
https://riptutorial.com/ 33
Chapter 11: DayPilot Scheduler
Parameters
Parameter Desc
DataStartField specifies the data source column that contains event start (DateTime)
DataStartField specifies the data source column that contains event start (DateTime)
DataEndField specifies the data source column that contains event end (DateTime)
DataTextField specifies the data soruce column that contains event text (string)
specifies the data soruce column that contains event resource foreign
DataResourceField
key (string)
Remarks
This is basics of DayPilot schedular which needs to be further explore.
Examples
Basic Info
DayPilot Scheduler widget displays a time line for multiple resources. Supports AJAX and HTML5.
Automatic and manual localization. Full CSS styling support
Declaration
DataStartField="eventstart"
DataEndField="eventend"
DataTextField="name"
DataIdField="id"
DataResourceField="resource_id"
CellGroupBy="Month"
Scale="Day"
https://riptutorial.com/ 34
EventMoveHandling="CallBack"
OnEventMove="DayPilotScheduler1_EventMove" >
</DayPilot:DayPilotScheduler>
https://riptutorial.com/ 35
Chapter 12: Directives
Examples
The Application Directive
The Application directive defines application-specific attributes. It is provided at the top of the
global.aspx file. The basic syntax of Application directive is:
Attributes Description
Description The text description of the application. Parsers and compilers ignore this.
The control directive is used with the user controls and appears in the user control (.ascx) files.
Attributes Description
The Boolean value that indicates whether view state is maintained across
EnableViewState
page requests.
https://riptutorial.com/ 36
Attributes Description
Explicit For VB language, tells the compiler to use option explicit mode.
Strict For VB language, tells the compiler to use the option strict mode.
The Implement directive indicates that the web page, master page or user control page must
implement the specified .Net framework interface.
The Master directive specifies a page file as being the mater page.
The Import directive imports a namespace into a web page, user control page of application. If the
Import directive is specified in the global.asax file, then it is applied to the entire application. If it is
in a page of user control page, then it is applied to that page or control.
The MasterType directive assigns a class name to the Master property of a page, to make it
strongly typed.
https://riptutorial.com/ 37
The Page Directive
The Page directive defines the attributes specific to the page file for the page parser and the
compiler.
Attributes Description
The Boolean value that enables or disables page events that are being
AutoEventWireup
automatically bound to methods; for example, Page_Load.
Buffer The Boolean value that enables or disables HTTP response buffering.
ClientTarget The browser for which the server controls should render content.
The Boolean value that enables or disables view state across page
EnableViewState
requests.
https://riptutorial.com/ 38
Attributes Description
The Boolean value that indicates whether all input data is validated
ValidateRequest
against a hardcoded list of values.
The OutputCache directive controls the output caching policies of a web page or a user control.
https://riptutorial.com/ 39
Chapter 13: Event Delegation
Syntax
1. public delegate void ActionClick();
Remarks
I haven't found any disadvantages in this approach but there are a few things which make this a
little problematic.
1. You need to add an event handler for each and every event. If you do not add the event
handlers in the OnInit event of the page, you might face some problems that on page post
back, you will lose the event assignment (as ASP.NET is stateless, which is not the case
with Windows controls).
2. In this approach, you need to respect the page life cycle events. Some times when you are
working on the Designer, there might be a case when the event handler gets lost without
your notice.
3. Even if you have not added the event handler, you will not get any errors or warnings. If you
have multiple pages for performing the same action, there is no guarantee that all the
method names will be same; the developer can choose their own method names, which
reduces the maintainability of the code.
Examples
Delegation of Event from User Control to aspx
Normally, we opt this approach if we want complete encapsulation and don't want to make our
methods public.
Ascx
Ascx.cs
https://riptutorial.com/ 40
public delegate void ActionClick();
The user control specifies some public events like OnAddClick, OnEditClick,etc., which declare a
delegate. Anyone who wants to use these events needs to add the EventHandler to execute when
the corresponding button click event occurs.
Aspx Design
https://riptutorial.com/ 41
<div>
<uc1:Direct ID="Direct1" runat="server" />
</div>
</form>
</body>
</html>
Aspx.cs
https://riptutorial.com/ 42
Chapter 14: Event Handling
Syntax
• private void EventName (object sender, EventArgs e);
Parameters
Parameter Details
object sender refers to the object that invoked the event that fired the event handler.
sender This is useful if you have many objects using the same event handler.
EventArgs is something of a dummy base class. In and of itself it's more or less
EventArgs
useless, but if you derive from it, you can add whatever data you need to pass
e
to your event handlers.
Examples
Application and Session Events
Session_Start - It is raised when a user first requests a page from the application.
https://riptutorial.com/ 43
PreRender - It is raised when the page or the control is to be rendered.
Default Events
The default event for the Page object is Load event. Similarly, every control has a default event.
For example, default event for the button control is the Click event.
The default event handler could be created in Visual Studio, just by double clicking the control in
design view. The following table shows some of the default events for common controls:
AdRotator AdCreated
BulletedList Click
Button Click
Calender SelectionChanged
CheckBox CheckedChanged
CheckBoxList SelectedIndexChanged
DataGrid SelectedIndexChanged
DataList SelectedIndexChanged
DropDownList SelectedIndexChanged
HyperLink Click
ImageButton Click
ImageMap Click
LinkButton Click
ListBox SelectedIndexChanged
RadioButton CheckedChanged
RadioButtonList SelectedIndexChanged
Example This example includes a simple page with a label control and a button control on it. As
the page events such as Page_Load, Page_Init, Page_PreRender etc. take place, it sends a
https://riptutorial.com/ 44
message, which is displayed by the label control. When the button is clicked, the Button_Click
event is raised and that also sends a message to be displayed on the label.
Create a new website and drag a label control and a button control on it from the control tool box.
Using the properties window, set the IDs of the controls as .lblmessage. and .btnclick.
respectively. Set the Text property of the Button control as 'Click'.
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblmessage" runat="server" >
</asp:Label>
<br />
<br />
<br />
</html>
Double click on the design view to move to the code behind file. The Page_Load event is
automatically created without any code in it. Write down the following self-explanatory code lines:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
https://riptutorial.com/ 45
namespace eventdemo {
if (Page.IsPostBack) {
lblmessage.Text += "Page post back event handled.<br/>";
}
}
Execute the page. The label shows page load, page initialization and, the page pre-render events.
Click the button to see effect:
https://riptutorial.com/ 46
Chapter 15: Expressions
Examples
Value From App.Config
Evaluated Expression
<div>
The time is now <%= DateTime.Now.ToString() %>
</div>
<div>
<form id="form1" runat="server">
<%
for (int i = 1; i <= 10; j++)
{
Response.Write(i) + " ";
}
%>
</form>
<div>
https://riptutorial.com/ 47
Chapter 16: Find Control by ID
Syntax
1. control.FindControl("Id Of The Control To Be Found")
Remarks
• FindControl is not recursive, it only searches through immediate children of the control
• There is an overload FindControl(String, int) which is not indented for public usage
• If nothing is found, FindControl returns null, so this is often a good idea to verify result for
being not null
Examples
Accessing the TextBox Control in aspx Page
Or if it has items.
https://riptutorial.com/ 48
Chapter 17: GridView
Examples
Data Binding
There are two ways you can bind a GridView. You can either manually do it by setting the
DataSource property and calling DataBind(), or you can use a DataSourceControl such as a
SqlDataSource.
Manual Binding
Create your GridView:
First create or retrieve the source data for the GridView. Next, assign the data to the GridView's
DataSource property. Finally, call DataBind().
gvColors.DataSource = colors;
gvColors.DataBind();
DataSourceControl
Create your DataSourceControl:
<asp:SqlDataSource ID="sdsColors"
runat="server"
ConnectionString="<%$ MyConnectionString %>"
SelectCommand="SELECT Color_Name FROM Colors">
</asp:SqlDataSource>
<asp:GridView ID="gvColors"
runat="server"
DataSourceID="sdsColors">
</asp:GridView>
Columns
There are seven different column types that can be used within a GridView.
https://riptutorial.com/ 49
<asp:GridView ID="GridView1" runat="server">
<Columns>
...
</Columns>
</asp:GridView>
BoundField:
ButtonField:
CheckBoxField:
CommandField:
<asp:CommandField ShowDeleteButton="true"
ShowEditButton="true"
ShowInsertButton="true"
ShowSelectButton="true" />
HyperLinkField:
ImageField:
<asp:ImageField HeaderText="Photo"
DataImageUrlField="EmployeeID"
DataImageUrlFormatString="/images/{0}" />
TemplateField:
<asp:TemplateField>
<HeaderTemplate>
Name
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblEmployeeName"
runat="server"
Text='<&# Eval("EmployeeName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
https://riptutorial.com/ 50
Starting with Asp.net 4.5 web controls can take advantage from strongly-typed binding to get
IntelliSense support and compiletime errors.
Grid.DataSource = albumList;
Grid.DataBind();
GridViews allow commands to be sent from a GridView row. This is useful for passing row-specific
information into an event handler as command arguments.
https://riptutorial.com/ 51
<asp:GridView ID="GridView1" ... OnRowCommand="GridView1_RowCommand">
Buttons are the most common way to raise commands. They also support a way to specify
command arguments. In this example, the argument is an ID of the item that the row represents.
<TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server"
CommandName="SampleCmd"
CommandArgument='<%# Eval("ID") %>'>
</asp:LinkButton>
</ItemTemplate>
</TemplateField>
Alternatively, one can use a CommandField column template that provides the most common
command controls.
Note that the CommandName used in this example is arbitrary and is a choice of the developer. There
is, however, a set of predefined names that the GridView itself recognizes. Corresponding events
are raised when these commands are fired.
Cancel RowCancelingEdit
Edit RowEditing
Paging
ObjectDataSource
https://riptutorial.com/ 52
If using an ObjectDataSource, almost everything is handled for you already, just simply tell the
GridView to AllowPaging and give it a PageSize.
<asp:GridView ID="gvColors"
runat="server"
DataSourceID="sdsColors"
AllowPaging="True"
PageSize="5">
</asp:GridView>
<asp:SqlDataSource ID="sdsColors"
runat="server"
ConnectionString="<%$ MyConnectionString %>"
SelectCommand="SELECT Color_ID, Color_Name FROM Colors">
</asp:SqlDataSource>
Manual Binding
If binding manually, you must handle the PageIndexChanging event. Simply set the DataSource and
PageIndex and re-bind the GridView.
<asp:GridView ID="gvColors"
runat="server"
AllowPaging="True"
PageSize="5"
OnPageIndexChanging="gvColors_PageIndexChanging">
</asp:GridView>
C#
VB.NET
https://riptutorial.com/ 53
}
Gridviews are more useful if we can update the view as per our need. Consider a view with a
lock/unlock feature in each row. It can be done like:
<Triggers>
</Triggers>
</asp:UpdatePanel>
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="imgDownload" runat="server" OnClientClick="return
confirm('Are you sure want to Lock/Unlock ?');"
CommandName="togglelock"
CommandArgument='<%#Container.DataItemIndex%>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</ContentTemplate>
Here we are giving our GridView1 one constant column, for lock button. Mind it, databind has not
taken place till now.
Lock/Unlock image will be different as per the value of a certain column in your GridView.
https://riptutorial.com/ 54
Consider a case where your table contains an attribute/column titled "Lock Status". Now you wish
to (1) hide that column just after DataBind and just before page rendering and (2) Assign different
images to each row on basis of that hidden column value i.e. if Lock Status for a row is 0, assign it
"lock.jpg", if status is 1 assign it "unlock.jpg". To do this, we'll use OnRowDataBound option of
GridView, it mingles with your GridView, just before rendering each row to the HTML page.
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound"> ...
In cs file
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[8].Visible = false; //hiding the desired column which is column number
8 in this case
GridView1.HeaderRow.Cells[8].Visible = false; //hiding its header
ImageButton imgDownload = (ImageButton)e.Row.FindControl("imgDownload");
string lstate = ((CheckBox)e.Row.Cells[8].Controls[0]).Checked.ToString();
if (lstate == "True")
{ imgDownload.ImageUrl = "images/lock.png"; }
else
{
imgDownload.ImageUrl = "images/unlock.png";
}
}
}
Now the GridView will be rendered as we want, now let us implement button click events on that
Lock/Unlock image button. Understand, that to perform a specific operation on a specific row, a
command has to be given to that row and GridView provides us with the same functionality named
OnRowCommand.
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound"
OnRowCommand="GridView1_RowCommand">
...
</ContentTemplate>
It'll create a function in cs file which takes an object sender and GridViewCommandEventArgs e With
e.CommandArgument we can get the index of the row which gave the command Point to be noted here
is that, a row can have multiple buttons and the cs code needs to know which button from that row
gave the command. So we'll use CommandName
Now in the backend one can distinguish commands from different rows and different buttons.
https://riptutorial.com/ 55
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "togglelock")
{
using (SqlConnection con= new SqlConnection(connectionString))
{
int index = Convert.ToInt32(e.CommandArgument);
SqlCommand sqlCommand = new SqlCommand(" ... ", con);
SqlDataReader reader = sqlCommand.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
}
}
}
Add <asp:PostBackTrigger ControlID="GridView1"/> to the Trigger and it will update the GridView
once the DataBind is done.
https://riptutorial.com/ 56
Chapter 18: httpHandlers
Examples
Using an httpHandler (.ashx) to download a file from a specific location
Create a new httpHandler inside your ASP.NET project. Apply the following code (VB) to the
handler file:
' pass an ID through the query string to append a unique identifer to your
downloadable fileName
context.Response.Clear()
context.Response.ContentType = "application/x-please-download-me" ' "application/x-
unknown"
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" &
fileName)
context.Response.BinaryWrite(byteArray)
context.Response.Flush()
context.Response.Close()
byteArray = Nothing
End Sub
End Class
You can call the handler from code behind, or from a client side language. In this example I am
using a javascript which will call the handler.
function openAttachmentDownloadHandler(fileId) {
https://riptutorial.com/ 57
var url = "..\\_Handlers\\AttachmentDownload.ashx?";
url = url + "id=" + fileId;
// opening the handler will run its code, and it will close automatically
// when it is finished.
window.open(url);
Now attach that assign the javascript function to a button click event on a clickable element in your
web form. For example:
Or you can call the javascript function from the code behind as well:
ScriptManager.RegisterStartupScript(Page,
Page.GetType(),
"openAttachmentDownloadHandler",
"openAttachmentDownloadHandler(" & fileId & ");",
True)
Now when you click your button the httpHandler will get your file to the browser and ask the user if
they would like to download it.
https://riptutorial.com/ 58
Chapter 19: Katana
Introduction
What Is Katana? Katana is a set of open source components for building and hosting OWIN-
based web applications, maintained by the Microsoft Open Technologies Group.Katana provides
an implementation of the OWIN specification, and is in fact used in an increasing number of
ASP.NET project templates. Additionally, Katana provides a wide variety of ready-to-use
middleware components, ready for use in an OWIN-based application.
Examples
Example
namespace KatanaConsole
{
// use an alias for the OWIN AppFunc:
using AppFunc = Func<IDictionary<string, object>, Task>;
class Program
{
static void Main(string[] args)
{
WebApp.Start<Startup>("http://localhost:8080");
Console.WriteLine("Server Started; Press enter to Quit");
Console.ReadLine();
}
}
https://riptutorial.com/ 59
}
}
}
https://riptutorial.com/ 60
Chapter 20: Middleware
Parameters
Parameter Details
Remarks
The AppFunc type is just an alias for Func<IDictionary<string, object>, Task> type to shorten
method signatures, much like typedef in C++.
Examples
Output the request path and the time it took to process it
class RequestTimeMiddleware
{
private AppFunc _next;
https://riptutorial.com/ 61
{
app.Use<RequestTimeMiddleware>();
}
}
https://riptutorial.com/ 62
Chapter 21: Page Life Cycle
Examples
Life Cycle Events
PreInit - PreInit is the first event in page life cycle. It checks the IsPostBack property and
determines whether the page is a postback. It sets the themes and master pages, creates
dynamic controls, and gets and sets profile property values. This event can be handled by
overriding the OnPreInit method or creating a Page_PreInit handler.
Init - Init event initializes the control property and the control tree is built. This event can be
handled by overriding the OnInit method or creating a Page_Init handler.
InitComplete - InitComplete event allows tracking of view state. All the controls turn on view-state
tracking.
LoadViewState - LoadViewState event allows loading view state information into the controls.
LoadPostData - During this phase, the contents of all the input fields are defined with the tag are
processed.
PreLoad - PreLoad occurs before the post back data is loaded in the controls. This event can be
handled by overriding the OnPreLoad method or creating a Page_PreLoad handler.
Load - The Load event is raised for the page first and then recursively for all child controls. The
controls in the control tree are created. This event can be handled by overriding the OnLoad
method or creating a Page_Load handler.
LoadComplete - The loading process is completed, control event handlers are run, and page
validation takes place. This event can be handled by overriding the OnLoadComplete method or
creating a Page_LoadComplete handler
PreRender - The PreRender event occurs just before the output is rendered. By handling this
event, pages and controls can perform any updates before the output is rendered.
PreRenderComplete - As the PreRender event is recursively fired for all child controls, this event
ensures the completion of the pre-rendering phase.
SaveStateComplete - State of control on the page is saved. Personalization, control state and
view state information is saved. The HTML markup is generated. This stage can be handled by
overriding the Render method or creating a Page_Render handler.
UnLoad - The UnLoad phase is the last phase of the page life cycle. It raises the UnLoad event
for all controls recursively and lastly for the page itself. Final cleanup is done and all resources and
https://riptutorial.com/ 63
references, such as database connections, are freed. This event can be handled by overriding the
OnUnLoad method or creating a Page_UnLoad handler.
Code Example
using System;
namespace myProject
{
public partial class WebForm1 : System.Web.UI.Page
{
public string PageSteps = string.Empty;
//Raised after the start stage is complete and before the initialization stage begins.
protected void Page_PreInit(object sender, EventArgs e)
{
PageSteps += "1 - Page_PreInit<br>";
//Raised after all controls have been initialized and any skin settings have been
applied.
//The Init event of individual controls occurs before the Init event of the page.
protected void Page_Init(object sender, EventArgs e)
{
PageSteps += "2 - Page_Init<br>";
//Raised after the page loads view state for itself and all controls, and after it
processes postback data that is included with the Request instance.
protected override void OnPreLoad(EventArgs e)
{
PageSteps += "4 - OnPreLoad<br>";
//The Page object calls the OnLoad method on the Page object, and then recursively
does the same for each child control until the page and all controls are loaded.
https://riptutorial.com/ 64
//The Load event of individual controls occurs after the Load event of the page.
protected void Page_Load(object sender, EventArgs e)
{
PageSteps += "5 - Page_Load<br>";
//Use these events to handle specific control events, such as a Button control's Click
event or a TextBox control's TextChanged event.
protected void btnSubmit_Click(object sender, EventArgs e)
{
//Step only visible on PostBack
PageSteps += "6 - btnSubmit_Click<br>";
//Raised after the Page object has created all controls that are required in order to
render the page, including child controls of composite controls.
//(To do this, the Page object calls EnsureChildControls for each control and for the
page.)
protected override void OnPreRender(EventArgs e)
{
PageSteps += "8 - OnPreRender<br>";
//Raised after each data bound control whose DataSourceID property is set calls its
DataBind method.
protected override void OnPreRenderComplete(EventArgs e)
{
PageSteps += "9 - OnPreRenderComplete<br>";
//Raised after view state and control state have been saved for the page and for all
controls.
//Any changes to the page or controls at this point affect rendering, but the changes
will not be retrieved on the next postback.
protected override void OnSaveStateComplete(EventArgs e)
{
PageSteps += "10 - OnSaveStateComplete<br><hr><br>";
// Render
//This is not an event; instead, at this stage of processing, the Page object calls
this method on each control.
https://riptutorial.com/ 65
//All ASP.NET Web server controls have a Render method that writes out the control's
markup to send to the browser.
Add the following code to the .aspx page to visualize the Steps in the Life Cycle.
More information
• https://msdn.microsoft.com/en-us/library/ms178472.aspx
• https://www.tutorialspoint.com/asp.net/asp.net_life_cycle.htm
• http://www.c-sharpcorner.com/UploadFile/8911c4/page-life-cycle-with-examples-in-Asp-Net/
• https://www.codeproject.com/Articles/667308/ASP-NET-Page-Life-Cycle-Events
https://riptutorial.com/ 66
Read Page Life Cycle online: https://riptutorial.com/asp-net/topic/4948/page-life-cycle
https://riptutorial.com/ 67
Chapter 22: Page Methods
Parameters
Parameter Detail
The parameter of the C# method. You supply the argument via the Page
limit
Method.
The JavaScript function that is executed when the Page Method call is
onSuccess
successful.
The JavaScript function that is executed when there is an error in the Page
onError
Method call.
Remarks
//C#
public static int SumValues(int num1, int num2, int num3, ..., int numN)
//JS
PageMethods.SumValues(num1, num2, num3, ..., numN, onSuccess, onError);
Return value
In the onSuccess function the result is going to be the C# function's return value. In the onError
function the result is going to be the error.
Examples
How to call it
Just add the using at the beginning and the [WebMethod] decorator to the static method to be called
in the aspx page:
using System.Web.Services;
https://riptutorial.com/ 68
public partial class MyPage : System.Web.UI.Page
{
[WebMethod]
public static int GetRandomNumberLessThan(int limit)
{
var r = new Random();
return r.Next(limit);
}
}
https://riptutorial.com/ 69
Chapter 23: Repeater
Examples
Basic usage
This example creates a simple 1-column repeater that displays a list of numbers, one per repeater
item.
Markup:
Code behind:
https://riptutorial.com/ 70
Chapter 24: ScriptManager
Introduction
ScriptManager control registers the script for the Microsoft AJAX Library with the page. This
enables client script support features such as partial-page rendering and Web-service calls.
Syntax
1. <asp:ScriptManager ID="smPop" runat="server"></asp:ScriptManager>
2. ScriptManager.RegisterStartupScript(Control,Type,String,String,Boolean);
Examples
Working with ScriptManager
You must use a ScriptManager control on a page to enable the following features of ASP.NET
AJAX:
1. Client-script functionality of the Microsoft AJAX Library, and any custom script that you want to
send to the browser.
3. JavaScript proxy classes for Web services, which enable you to use client script to access Web
services by exposing Web services as strongly typed objects.
[WebMethod]
public int Add(int a, int b) { return a + b; }
function CallAdd()
{
// method will return immediately
// processing done asynchronously
WebService.Add(0,6, OnMethodSucceeded, OnMethodFailed);
}
https://riptutorial.com/ 71
Sys.Services.AuthenticationService.login
Sys.Services.AuthenticationService.logout
<script type="text/javascript">
function MyMethod(username, password)
{
Sys.Services.AuthenticationService.login(username,
password,false,null,null,null,null,"User Context");
}
</script>
https://riptutorial.com/ 72
Chapter 25: Session Managment
Examples
Advantage and Disadvantage of Session State, types of session
1)Better security
2)Reduced bandwidth
1) InProc mode, which stores session state in memory on the Web server. This is the
default.
2) StateServer mode, which stores session state in a separate process called the ASP.NET
state service. This ensures that session state is preserved if the Web application is
restarted and also makes session state available to multiple Web servers in a Web farm.
3) SQLServer mode stores session state in a SQL Server database. This ensures that session
state is preserved if the Web application is restarted and also makes session state available
to multiple Web servers in a Web farm.
https://riptutorial.com/ 73
Chapter 26: Session State
Syntax
• Session["Session_Key"] = Obj_Value;
Remarks
HTTP is stateless. ASP.NET session state is a framework that facilitates maintaining state
between HTTP page requests.
Session differs from the class level variables in its ability to remain available across post-backs
and different pages. For instance, a session variable created in Page1.aspx will be available if the
user is redirected to Page2.aspx afterwards, within the same application.
Also, in contrast to static variables declared at the page level, the session variables are
independent for different users. Meaning, changing the value of one user's session variable will
not affect the value of the same variable for other users.
While ViewState can be used to store user's data temporarily, it doesn't allow saving data across
multiple pages. In addition, the viewstate is part of the page and is sent to the client. As a result,
any critical information related to the user cannot be saved in the ViewState, and that's where
Session variables become useful.
Examples
Using the Session object to store values
https://riptutorial.com/ 74
bool showWarnings = (bool)HttpContext.Current.Session["showWarnings"];
lblWarnings.Visible = false;
}
}
Note that the session variables are not common for all users (just like cookies), and they are
persisted across multiple post-backs.
The session works by setting a cookie that contains an identifier for the users session. By default
this identifier is stored in the web-server memory, along with the values stored against it.
Here is a screenshot of the cookie set in the user's browser to keep track of the session:
If you find that you have multiple servers that need to share session state, storing it in the
ASP.NET process memory will not work. For example you may deploy into a web-farm
environment with a load balancer that distributes requests in a round-robin fashion. In this
environment a single user's requests could be served by multiple servers.
In the web.config file you can configure a SQL server session store.
<configuration>
<system.web>
<sessionState
mode="SQLServer"
sqlConnectionString="Data Source=localhost;Integrated Security=SSPI"
cookieless="true"
timeout="30" />
</system.web>
</configuration>
To create the sql schema use the aspnet_regsql tool. [SampleSqlServerName] is the hostname of
the SQL server. -ssadd tells the tool to create the session state database. -sstype p tells the tool to
create a new database with the default name ASPState.
If you don't want to use SQL server you can use Amazon's hosted Dynamo DB nosql database as
a session store.
You'll need the AWS SDK. To install this from the Visual Studio nuget package manager console
use the following command
https://riptutorial.com/ 75
Install-Package AWSSDK
You can then configure your sessionState provider to use a custom provider. You must specify the
region and credentials, either a profile or an IAM access and secret key combination. By default
this will create a table named ASP.NET_SessionState.
<configuration>
<system.web>
<sessionState
timeout="20"
mode="Custom"
customProvider="DynamoDBSessionStoreProvider">
<providers>
<add name="DynamoDBSessionStoreProvider"
type="Amazon.SessionProvider.DynamoDBSessionStateStore"
AWSProfileName="[PROFILE]"
Region="[REGION]"
CreateIfNotExist="true"
/>
</providers>
</sessionState>
</system.web>
</configuration>
https://riptutorial.com/ 76
Chapter 27: UpdatePanel
Introduction
This topic describes how to add partial-page update support to a Web page by using two Microsoft
Ajax server controls: the ScriptManager control and the UpdatePanel control. These controls
remove the requirement to refresh the whole page with each postback, which improves the user
experience.
Syntax
• <asp:UpdatePanel ID="UpdatePanel1" runat="server">
</asp:UpdatePanel>
Remarks
A ScriptManager must be added to page to make the UpdatePanel to work.
Examples
Update Panel Example
Step 3: After adding content to your UpdatePanels Content Template your aspx page should look
something like this:
https://riptutorial.com/ 77
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div style="padding-top: 10px">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<fieldset>
<legend>UpdatePanel</legend>
<asp:Label ID="Label1" runat="server" Text="Panel created."></asp:Label><br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button"
/>
</fieldset>
</ContentTemplate>
</asp:UpdatePanel>
<br />
</div>
</div>
</form>
</body>
</html>
Expected Result:
The panel content changes every time that you click the button, but the whole page is not
refreshed. By default, the ChildrenAsTriggers property of an UpdatePanel control is true. When
this property is set to true, controls inside the panel participate in partial-page updates when any
control in the panel causes a postback.
https://riptutorial.com/ 78
Chapter 28: View State
Introduction
View State is the method to preserve the Value of the Page and Controls between round trips. It is
a Page-Level State Management technique. View State is turned on by default and normally
serializes the data in every control on the page regardless of whether it is actually used during a
post-back.
Syntax
• ViewState["NameofViewstate"] = "Value";
Examples
Example
ASPX
Code behind
using System;
using System.Data;
using System.Web;
https://riptutorial.com/ 79
NameLabel.Text = ViewState["NameOfUser"].ToString();
else
NameLabel.Text = "Not set yet...";
}
https://riptutorial.com/ 80
Chapter 29: web.config >
system.webServer/httpErrors &
system.web/customErrors sections
Introduction
CustomErrors are a legacy (backwards compatable) element, used by Visual Studio Development
Server (aka. VSDS or Cassini).
Examples
What is the difference between customErrors and httpErrors?
Both are used to define error handling for a website, but different software refers to
different config elements.
customErrors are a legacy (backwards compatable) element, used by Visual Studio Development
Server (aka. VSDS or Cassini).
This highlights the possible problem when developing ASP.NET websites while using VSDS
instead of the local IIS.
Also, refer to this post by myself about how to handle error messages with IIS7, if you wish to have
full control of the error output.
Summary:
https://riptutorial.com/ 81
Chapter 30: WebForms
Syntax
• <asp:TextBox runat="server" ID="" TextMode="" Text="" />
• <asp:Repeater runat="server" ID="" OnItemDataBound="">
<HeaderTemplate></HeaderTemplate>
<ItemTemplate></ItemTemplate>
<FooterTemplate></FooterTemplate>
</asp:Repeater>
Remarks
All ASP.Net WebForm controls require runat="server" in order to communicate with the
CodeBehind.
Examples
Using a Repeater to create a HTML Table
When the Repeater is Bound, for each item in the data, a new table row will be added.
https://riptutorial.com/ 82
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
The ItemDataBound method is optional, yet useful for formatting or populating more complicated
data. In this example, the method is used to dynamically give each <tr> a unique ID. This ID can
then be use in JavaScript to access or modify a specific row. Note, the tr will not keep its dynamic
ID value on PostBack. The text of each row's <asp:Label> was also set in this method.
If you plan on doing a lot of communication with the CodeBehind, you might want to consider
using GridView. Repeaters, however, in general have less overhead than GridView, and with basic
ID manipulation, can perform the same functions as GridView.
Grouping in ListView
Markup
https://riptutorial.com/ 83
<img src='<%# Container.DataItem %>' />
</li>
</ItemTemplate>
</asp:ListView>
Code Behind
CSS
.images-list ul{
clear: both;
list-style-type: none;
}
.images-list ul li{
float: left;
padding: 5px;
}
Rendered Output
https://riptutorial.com/ 84
Example
</script>
<form runat="server">
<p>
</form>
Hyperlink
The HyperLink control is used to navigate from the client to another page.
<html>
https://riptutorial.com/ 85
' Set hyperlink to "~", which indicates application root.
HyperLink1.NavigateUrl = "~"
End Sub
</script>
<body>
<form runat=server>
<p>
</form>
</body>
</html>
https://riptutorial.com/ 86
Chapter 31: WebService without Visual
Studio
Introduction
A very basic ASP.Net example of the bare minimum of code to create a WebService.
Remarks
In a separate StackOverflow Documentation post, we'll look at consuming this Calculator
WebService.
Examples
Calculator WebService
[WebMethod]
public int CalculatorSubtract(int operandA, int operandB)
{
return operandA - operandB;
}
[WebMethod]
public long CalculatorMultiply(int operandA, int operandB)
{
return operandA * operandB;
}
[WebMethod]
public long CalculatorDivide(int operandNumerator, int operandDenominator)
{
if (operandDenominator == 0)
return System.Int64.MaxValue; // Should really do better error handling overall
& return an error
else
return operandNumerator / operandDenominator;
}
}
https://riptutorial.com/ 87
Read WebService without Visual Studio online: https://riptutorial.com/asp-
net/topic/8859/webservice-without-visual-studio
https://riptutorial.com/ 88
Credits
S.
Chapters Contributors
No
15 Expressions Ryan
19 Katana jignesh
20 Middleware Marco
https://riptutorial.com/ 89
22 Page Methods Enrique Zavaleta, wazz, XIII
23 Repeater Andrei
web.config >
system.webServer/httpErrors
29 Naveen Gogineni
& system.web/customErrors
sections
https://riptutorial.com/ 90