The document discusses various ASP.NET server-side tags used in web forms. It provides the tag name, a brief description of its usage, and a link to the Microsoft documentation for each tag. The tags covered are: <% %> for code blocks, <%= %> for single-value expressions, <%# %> for data binding expressions, <%$ %> for expressions in data sources, <%@ %> for directives, <%-- --%> for comments, and <%: %> for HTML encoding.
1. <% ... %>
The most basic inline tag, basically runs normal code:
<% if (User.IsInRole("admin")) { %>
You can see this
<% } else { %>
You are no admin fool!
<%} %>
http://msdn2.microsoft.com/en-us/library/ms178135(vs.80).aspx
<%= ... %>
Used for small chunks of information, usually from objects and single pieces of information like a single
string or int variable:
The Date is now <%= DateTime.Now.ToShortDateString() %>
The value of string1 is <%= string1 %>
http://msdn2.microsoft.com/en-us/library/6dwsdcf5(VS.71).aspx
*note: <%= is the equivalent of Response.Write() - Courtesy of Adam from the US,thanks!
<%# .. %>
Used for Binding Expressions; such as Eval and Bind, most often found in data controls like GridView,
Repeater, etc.:
<asp:Repeater ID="rptMeetings" DataSourceID="meetings"
runat="server">
<ItemTemplate>
<%# Eval("MeetingName")%>
</ItemTemplate>
</asp:Repeater>
http://msdn2.microsoft.com/en-us/library/ms178366.aspx
<%$ ... %>
Used for expressions, not code; often seen with DataSources:
<asp:SqlDataSource ID="party" runat="server"
ConnectionString="<%$ ConnectionStrings:letsParty %>"
SelectCommand="SELECT * FROM [table]"
/>
http://msdn2.microsoft.com/en-us/library/d5bd1tad.aspx
<%@ ... %>
This is for directive syntax; basically the stuff you see at the top your your aspx pages like control
registration and page declaration:
<%@ Page Language="C#"
MasterPageFile="~/MasterPage.master"
2. AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" Title="Untitled Page" %>
<%@ Register TagPrefix="wp" Namespace="CustomWebParts" %>
http://msdn2.microsoft.com/en-us/library/xz702w3e(VS.80).aspx
<%-- ... --%>
This is a server side comment, stuff you don't want anyone without code access to see:
<asp:Label ID="lblAwesome" runat="server"/>
<%-- sometimes end users make me angry --%>
<asp:LinkButton ID="lbEdit" Text="Edit"
OnClick="Edit_Click" runat="server" />
http://msdn2.microsoft.com/en-us/library/4acf8afk.aspx
<%: ... %>
This tag is identical to the "<%= ... %>" tag except that it auto-html-encodes the value within the tag.
As Phil Haack said:I often tell people it’s <%= but with the = seen from the front.:
<%: Html.TextBox("FirstName") %>
ASP is run under the inetinfo.exe(IIS) process space and hence susceptible to application crashes as a
result the IIS needs to be stopped or restarted. ASP is related to the process isolation setting in IIS.
But, ASP.Net
The ASP.NET worker process is a distinct worker process, aspnet_wp.exe, separate
from inetinfo.exe ( IIS process), and the process model in ASP.NET is unrelated to process isolation
settings in IIS.
Note :- IIS is still the entry point to a ASP.NET application
3. Name Description
AccessKey Gets or sets the access key that allows you to quickly navigate to the Web server
control. (Inherited from WebControl.)
Adapter Gets the browser-specific adapter for the control. (Inherited from Control.)
AllowCustomPaging Gets or sets a value that indicates whether custom paging is enabled.
AllowPaging Gets or sets a value indicating whether the paging feature is enabled.
AllowSorting Gets or sets a value indicating whether the sorting feature is enabled.
AlternatingRowStyle Gets a reference to the TableItemStyle object that enables you to set the appearance
of alternating data rows in a GridViewcontrol.
AppRelativeTemplateSourceDirector Gets or sets the application-relative virtual directory of thePage or UserControl object
y that contains this control.(Inherited from Control.)
Attributes Gets the collection of arbitrary attributes (for rendering only) that do not correspond
to properties on the control. (Inherited from WebControl.)
AutoGenerateColumns Gets or sets a value indicating whether bound fields are automatically created for
each field in the data source.
AutoGenerateDeleteButton Gets or sets a value indicating whether a CommandField field column with a Delete
button for each data row is automatically added to a GridView control.
AutoGenerateEditButton Gets or sets a value indicating whether a CommandField field column with an Edit
button for each data row is automatically added to a GridView control.
AutoGenerateSelectButton Gets or sets a value indicating whether a CommandField field column with a Select
button for each data row is automatically added to a GridView control.
BackColor Gets or sets the background color of the Web server control.(Inherited
from WebControl.)
BackImageUrl Gets or sets the URL to an image to display in the background of a GridView control.
4. BindingContainer Infrastructure. Gets the control that contains this control's data binding. (Inherited
from Control.)
BorderColor Gets or sets the border color of the Web control. (Inherited from WebControl.)
BorderStyle Gets or sets the border style of the Web server control.(Inherited from WebControl.)
BorderWidth Gets or sets the border width of the Web server control.(Inherited from WebControl.)
BottomPagerRow Gets a GridViewRow object that represents the bottom pager row in
a GridView control.
Caption Gets or sets the text to render in an HTML caption element in a GridView control.
This property is provided to make the control more accessible to users of assistive
technology devices.
CaptionAlign Gets or sets the horizontal or vertical position of the HTML caption element in
a GridView control. This property is provided to make the control more accessible to
users of assistive technology devices.
CellPadding Gets or sets the amount of space between the contents of a cell and the cell's border.
CellSpacing Gets or sets the amount of space between cells.
ChildControlsCreated Gets a value that indicates whether the server control's child controls have been
created. (Inherited from Control.)
ClientID Gets the control ID for HTML markup that is generated by ASP.NET. (Inherited
from Control.)
ClientIDMode Gets or sets the algorithm that is used to generate the value of
the ClientID property. (Inherited from Control.)
ClientIDRowSuffix Gets or sets the names of the data fields whose values are appended to
the ClientID property value to uniquely identify each instance of a data-bound
control.
ClientIDRowSuffixDataKeys Infrastructure. Gets the data values that are used to uniquely identify each instance of
a data-bound control when ASP.NET generates the ClientID value.
5. ClientIDSeparator Gets a character value representing the separator character used in
the ClientID property. (Inherited from Control.)
Columns Gets a collection of DataControlField objects that represent the column fields in
a GridView control.
ColumnsGenerator Gets or sets the control that will automatically generate the columns for
a GridView control that uses ASP.NET Dynamic Data features.
Context Gets the HttpContext object associated with the server control for the current Web
request. (Inherited from Control.)
Controls Gets a collection of the child controls within the composite data-bound
control. (Inherited fromCompositeDataBoundControl.)
ControlStyle Gets the style of the Web server control. This property is used primarily by control
developers. (Inherited from WebControl.)
ControlStyleCreated Gets a value indicating whether a Style object has been created for
the ControlStyle property. This property is primarily used by control
developers. (Inherited fromWebControl.)
CssClass Gets or sets the Cascading Style Sheet (CSS) class rendered by the Web server
control on the client. (Inherited fromWebControl.)
DataItemContainer Gets a reference to the naming container if the naming container
implements IDataItemContainer. (Inherited fromControl.)
DataKeyNames Gets or sets an array that contains the names of the primary key fields for the items
displayed in a GridView control.
DataKeys Gets a collection of DataKey objects that represent the data key value of each row in
a GridView control.
DataKeysContainer Gets a reference to the naming container if the naming container
implements IDataKeysControl. (Inherited fromControl.)
DataMember Gets or sets the name of the list of data that the data-bound control binds to, in cases
where the data source contains more than one distinct list of data items. (Inherited
6. fromDataBoundControl.)
DataSource Gets or sets the object from which the data-bound control retrieves its list of data
items. (Inherited fromBaseDataBoundControl.)
DataSourceID Gets or sets the ID of the control from which the data-bound control retrieves its list
of data items. (Inherited fromDataBoundControl.)
DataSourceObject Gets an object that implements the IDataSource interface, which provides access to
the object's data content. (Inherited from DataBoundControl.)
DeleteMethod Gets or sets the name of the method to call in order to delete data.
DesignMode Gets a value indicating whether a control is being used on a design surface. (Inherited
from Control.)
EditIndex Gets or sets the index of the row to edit.
EditRowStyle Gets a reference to the TableItemStyle object that enables you to set the appearance
of the row selected for editing in aGridView control.
EmptyDataRowStyle Gets a reference to the TableItemStyle object that enables you to set the appearance
of the empty data row rendered when aGridView control is bound to a data source
that does not contain any records.
EmptyDataTemplate Gets or sets the user-defined content for the empty data row rendered when
a GridView control is bound to a data source that does not contain any records.
EmptyDataText Gets or sets the text to display in the empty data row rendered when
a GridView control is bound to a data source that does not contain any records.
Enabled Gets or sets a value indicating whether the Web server control is enabled. (Inherited
from WebControl.)
EnableModelValidation Gets or sets a value that indicates whether a validator control will handle exceptions
that occur during insert or update operations.
EnablePersistedSelection Gets or sets a value that indicates whether the selection of a row is based on index or
on data-key values.
7. EnableSortingAndPagingCallbacks Gets or sets a value indicating whether client-side callbacks are used for sorting and
paging operations.
EnableTheming Gets or sets a value indicating whether themes apply to this control. (Inherited
from WebControl.)
EnableViewState Gets or sets a value indicating whether the server control persists its view state, and
the view state of any child controls it contains, to the requesting client. (Inherited
from Control.)
Events Gets a list of event handler delegates for the control. This property is read-
only. (Inherited from Control.)
Font Gets the font properties associated with the Web server control. (Inherited
from WebControl.)
FooterRow Gets a GridViewRow object that represents the footer row in aGridView control.
FooterStyle Gets a reference to the TableItemStyle object that enables you to set the appearance
of the footer row in a GridView control.
ForeColor Gets or sets the foreground color (typically the color of the text) of the Web server
control. (Inherited from WebControl.)
GridLines Gets or sets the gridline style for a GridView control.
HasAttributes Gets a value indicating whether the control has attributes set.(Inherited
from WebControl.)
HasChildViewState Gets a value indicating whether the current server control's child controls have any
saved view-state settings. (Inherited from Control.)
HeaderRow Gets a GridViewRow object that represents the header row in a GridView control.
HeaderStyle Gets a reference to the TableItemStyle object that enables you to set the appearance
of the header row in a GridView control.
Height Gets or sets the height of the Web server control. (Inherited from WebControl.)
8. HorizontalAlign Gets or sets the horizontal alignment of a GridView control on the page.
ID Gets or sets the programmatic identifier assigned to the server control. (Inherited
from Control.)
IdSeparator Infrastructure. Gets the character used to separate control identifiers. (Inherited
from Control.)
Initialized Gets a value indicating whether the data-bound control has been initialized. (Inherited
from BaseDataBoundControl.)
InsertMethod Gets or sets the name of the method to call in order to insert data. (Inherited
from CompositeDataBoundControl.)
IsBoundUsingDataSourceID Gets a value indicating whether the DataSourceID property is set. (Inherited
from BaseDataBoundControl.)
IsChildControlStateCleared Gets a value indicating whether controls contained within this control have control
state. (Inherited from Control.)
IsDataBindingAutomatic Gets a value that indicates whether data binding is automatic.(Inherited
from BaseDataBoundControl.)
IsEnabled Gets a value indicating whether the control is enabled.(Inherited from WebControl.)
IsTrackingViewState Gets a value that indicates whether the server control is saving changes to its view
state. (Inherited from Control.)
IsUsingModelBinders Gets a value that indicates whether model binding is in use.(Inherited
from CompositeDataBoundControl.)
IsViewStateEnabled Gets a value indicating whether view state is enabled for this control. (Inherited
from Control.)
ItemType Gets or sets the name of the data item type for strongly typed data binding. (Inherited
from DataBoundControl.)
LoadViewStateByID Gets a value indicating whether the control participates in loading its view state
by ID instead of index. (Inherited fromControl.)
9. NamingContainer Gets a reference to the server control's naming container, which creates a unique
namespace for differentiating between server controls with the
same Control.ID property value.(Inherited from Control.)
Page Gets a reference to the Page instance that contains the server control. (Inherited
from Control.)
PageCount Gets the number of pages required to display the records of the data source in
a GridView control.
PageIndex Gets or sets the index of the currently displayed page.
PagerSettings Gets a reference to the PagerSettings object that enables you to set the properties of
the pager buttons in a GridViewcontrol.
PagerStyle Gets a reference to the TableItemStyle object that enables you to set the appearance
of the pager row in a GridView control.
PagerTemplate Gets or sets the custom content for the pager row in aGridView control.
PageSize Gets or sets the number of records to display on a page in aGridView control.
Parent Gets a reference to the server control's parent control in the page control
hierarchy. (Inherited from Control.)
RenderingCompatibility Gets a value that specifies the ASP.NET version that rendered HTML will be
compatible with. (Inherited from Control.)
RequiresDataBinding Gets or sets a value indicating whether the DataBind method should be
called. (Inherited from BaseDataBoundControl.)
RowHeaderColumn Gets or sets the name of the column to use as the column header for
the GridView control. This property is provided to make the control more accessible
to users of assistive technology devices.
Rows Gets a collection of GridViewRow objects that represent the data rows in
a GridView control.
RowStyle Gets a reference to the TableItemStyle object that enables you to set the appearance
10. of the data rows in a GridView control.
SelectArguments Gets a DataSourceSelectArguments object that the data-bound control uses when
retrieving data from a data source control.(Inherited from DataBoundControl.)
SelectedDataKey Gets the DataKey object that contains the data key value for the selected row in
a GridView control.
SelectedIndex Gets or sets the index of the selected row in a GridViewcontrol.
SelectedPersistedDataKey Gets or sets the data-key value for the persisted selected item in a GridView control.
SelectedRow Gets a reference to a GridViewRow object that represents the selected row in the
control.
SelectedRowStyle Gets a reference to the TableItemStyle object that enables you to set the appearance
of the selected row in a GridViewcontrol.
SelectedValue Gets the data key value of the selected row in a GridViewcontrol.
SelectMethod The name of the method to call in order to read data.(Inherited
from DataBoundControl.)
ShowFooter Gets or sets a value indicating whether the footer row is displayed in
a GridView control.
ShowHeader Gets or sets a value indicating whether the header row is displayed in
a GridView control.
ShowHeaderWhenEmpty Gets or sets a value that indicates whether the heading of a column in
the GridView control is visible when the column has no data.
Site Gets information about the container that hosts the current control when rendered on
a design surface. (Inherited fromControl.)
SkinID Gets or sets the skin to apply to the control. (Inherited fromWebControl.)
SortDirection Gets the sort direction of the column being sorted.
11. SortedAscendingCellStyle Gets or sets the CSS style for a GridView column when the column is sorted in
ascending order.
SortedAscendingHeaderStyle Gets or sets the CSS style to apply to a GridView column heading when the column
is sorted in ascending order.
SortedDescendingCellStyle Gets or sets the style of a GridView column when the column is sorted in descending
order.
SortedDescendingHeaderStyle Gets or sets the style to apply to a GridView column heading when the column is
sorted in descending order.
SortExpression Gets the sort expression associated with the column or columns being sorted.
Style Gets a collection of text attributes that will be rendered as a style attribute on the
outer tag of the Web server control.(Inherited from WebControl.)
SupportsDisabledAttribute Gets a value that indicates whether the control should set thedisabled attribute of the
rendered HTML element to "disabled" when the control's IsEnabled property is false.
(Inherited from BaseDataBoundControl.)
TabIndex Gets or sets the tab index of the Web server control. (Inherited from WebControl.)
TagKey Gets the HtmlTextWriterTag value for the GridView control.
(Overrides WebControl.TagKey.)
TagName Gets the name of the control tag. This property is used primarily by control
developers. (Inherited from WebControl.)
TemplateControl Gets or sets a reference to the template that contains this control. (Inherited
from Control.)
TemplateSourceDirectory Gets the virtual directory of the Page or UserControl that contains the current server
control. (Inherited from Control.)
ToolTip Gets or sets the text displayed when the mouse pointer hovers over the Web server
control. (Inherited from WebControl.)
TopPagerRow Gets a GridViewRow object that represents the top pager row in a GridView control.
12. UniqueID Gets the unique, hierarchically qualified identifier for the server control. (Inherited
from Control.)
UpdateMethod Gets or sets the name of the method to call in order to update data.
UseAccessibleHeader Gets or sets a value indicating whether a GridView control renders its header in an
accessible format. This property is provided to make the control more accessible to
users of assistive technology devices.
ValidateRequestMode Gets or sets a value that indicates whether the control checks client input from the
browser for potentially dangerous values.(Inherited from Control.)
ViewState Gets a dictionary of state information that allows you to save and restore the view
state of a server control across multiple requests for the same page. (Inherited
from Control.)
ViewStateIgnoresCase Gets a value that indicates whether the StateBag object is case-insensitive. (Inherited
from Control.)
ViewStateMode Gets or sets the view-state mode of this control. (Inherited from Control.)
VirtualItemCount Gets or sets the virtual number of items in the data source that the GridView control
is bound to when custom paging is used.
Visible Gets or sets a value that indicates whether a server control is rendered as UI on the
page. (Inherited from Control.)
Width Gets or sets the width of the Web server control. (Inherited from WebControl.)
Explicit Interface Implementations
Name Description
IControlBuilderAccessor.ControlBuilder For a description of this member,
seeIControlBuilderAccessor.ControlBuilder. (Inherited from Control.)
IControlDesignerAccessor.UserData For a description of this member,
seeIControlDesignerAccessor.UserData. (Inherited fromControl.)
IDataBindingsAccessor.DataBindings For a description of this member,
13. seeIDataBindingsAccessor.DataBindings. (Inherited fromControl.)
IDataBindingsAccessor.HasDataBindings For a description of this member,
seeIDataBindingsAccessor.HasDataBindings. (Inherited from Control.)
IDataBoundControl.DataKeyNames Gets or sets the names of the primary key fields for the items displayed in a
data-bound control.
IDataBoundControl.DataMember Gets or sets the table that is exposed by the data source control to bind to the
data-bound control.
IDataBoundControl.DataSource Gets or sets the data source object from which the data-bound control retrieves
the list of data items.
IDataBoundControl.DataSourceID Gets or sets the ID of the data source from which the data-bound control
retrieves the list of data items.
IDataBoundControl.DataSourceObject Gets or sets the data source object from which the data-bound control retrieves
the list of data items.
IDataBoundListControl.ClientIDRowSuffix Gets or sets the names of the data fields whose values are appended to
the ClientID property value to uniquely identify each instance of a data-bound
control.
IDataBoundListControl.DataKeys Gets a collection of objects that represent theDataKeys value in a data-bound
control.
IDataBoundListControl.EnablePersistedSelecti Gets or sets a value that indicates whether the selection of a row is based on
on index or on data-key values.
IDataBoundListControl.SelectedDataKey Gets the object that contains the data key value for the selected row in a data-
bound control.
IDataBoundListControl.SelectedIndex Gets or sets the index of the selected row in the data-bound control.
IDataKeysControl.ClientIDRowSuffixDataKey Infrastructure. Gets the data values that are used to uniquely identify each
s instance of a data-bound control when ASP.NET generates the ClientID value.
IExpressionsAccessor.Expressions For a description of this member,
14. seeIExpressionsAccessor.Expressions. (Inherited fromControl.)
IExpressionsAccessor.HasExpressions For a description of this member,
seeIExpressionsAccessor.HasExpressions. (Inherited from Control.)
IFieldControl.FieldsGenerator Gets or sets the control that automatically generates the columns for a data-
bound control for use by ASP.NET Dynamic Data.
IPersistedSelector.DataKey For a description of this member, seeIPersistedSelector.DataKey.
Directory structure
In general, the ASP.NET directory structure can be determined by the developer's preferences. Apart
from a few reserved directory names, the site can span any number of directories. The structure is
typically reflected directly in the URLs. Although ASP.NET provides means for intercepting the request at
any point during processing, the developer is not forced to funnel requests through a central application
or front controller.
The special directory names (from ASP.NET 2.0 on) are:[13]
App_Code
This is the "raw code" directory. The ASP.NET server automatically compiles files (and
subdirectories) in this folder into an assembly which is accessible in the code of every page of the
site. App_Code will typically be used for data access abstraction code, model code and business
code. Also any site-specific http handlers and modules and Web service implementation go in
this directory. As an alternative to using App_Code the developer may opt to provide a separate
assembly with precompiled code.
App_Data
The App_Data ASP.NET Directory is the default directory for any database used by the
ASP.NET Website. These databases might include Access (mdb) files or SQL Server (mdf) files.
The App_Data is the only directory with Write Access enabled for the ASP.NET web application.:
[14]
App_LocalResources
E.g. a file called CheckOut.aspx.fr-FR.resx holds localized resources for the French version of
the CheckOut.aspx page. When the UI culture is set to French, ASP.NET will automatically find
and use this file for localization.
App_GlobalResources
15. Holds resx files with localized resources available to every page of the site. This is where the
ASP.NET developer will typically store localized messages etc. which are used on more than one
page.
App_Themes
Adds a folder that holds files related to themes which is a new ASP.NET feature that helps
ensure a consistent appearance throughout a Web site and makes it easier to change the Web
site’s appearance when necessary.
App_WebReferences
holds discovery files and WSDL files for references to Web services to be consumed in the site.
Bin
Contains compiled code (.dll files) for controls, components, or other code that you want to
reference in your application. Any classes represented by code in the Bin folder are automatically
referenced in your application.
Using the code
We are going to user C# as our language.
Start
Open Visual Studio and Create a New Website. Automatically you will have an
empty page defined for you like this
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
Go to Design View and you will notice there is nothing on your page. Now open
your Toolbox and add a buttons and some textbox and depicted in the following.
16. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblUsername" runat="server" Text="Username"></asp:Label>
<asp:TextBox ID="txtUsername" runat="server"></asp:TextBox>
<br />
<br />
<asp:Label ID="lblPassword" runat="server" Text="Password"></asp:Label>
<asp:TextBox ID="txtPassword" runat="server"
TextMode="Password"></asp:TextBox>
<br />
<br />
 
;
<asp:Button ID="btnlogin" runat="server" Text="Login" onclick="btnlogin_Click"
Width="47px" />
<asp:Button ID="btnCancel" runat="server" Text="Cancel"
onclick="btnCancel_Click" />
<br />
 
;
<asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>
</div>
</form>
</body>
</html>
And your Design should look like this
Now as you can see our login page is created, Let us see how we can validate the
login and what is needed to have a proper login. Open your Sql management Studio
and Create a New Database, but if you already have it you will just follow the Step
2 where we add a table.
17. Step 1: Create a Database
Create Database FORUM
Step 2: Create a Table
CREATE TABLE [dbo].[Log_Users]
(
[Logid] [int] IDENTITY(100,1)PRIMARY KEY NOT NULL,
[Username] [varchar](55) NOT NULL,
[PASSWORD][varchar](55),
[Time_Logged_in] [datetime] NOT NULL,
[Time_Logged_Out] [datetime] NOT NULL,
[Status] [int] NOT NULL,
[Date_Logged_in] [datetime] NOT NULL,
[E_MAIL] [varchar](55) NOT NULL
)
Step 3: Let us Add Sample Data
insert into dbo.Log_Users
values('Vuyiswamb','wowididit',GETDATE(),'02/07/2010',1,GETDATE(),'Vuyiswa@wow.com')
insert into dbo.Log_Users
values('SheoNarayan','Oops?',GETDATE(),'02/09/2010',1,GETDATE(),'Sheo@wowMail.com')
Now that we have our sample Data. Please note that you can use any other field
but the username and Password fields are the most important. Now let us create
our stored Procedure.
Step 4: Create a Stored Prcedure that will validate and return a valid Integer.
Create Proc [dbo].[prcLoginv]
(
@Username VarChar(50),
@UPassword varChar(50),
@OutRes int OUTPUT
)
AS
set @OutRes = (SELECT count(*) FROM [dbo].Log_Users
WHERE Username = @Username And [Password] = @UPassword)
if(@OutRes = 1)
begin
set @OutRes = 1--Login is Correct
end
else
begin
18. set @OutRes = 0 --Bad login
end
In the above Stored Procedure we count the Records that have matched the
Records and if there is one record found then it is a good login else it is a bad login.
But how will you use this in your asp.net Page. First we have to create a Function
that will access the stored procedure and call that function in click event of the
button. Create a Function as show below in your page not inside your page load
because you will get an Error.
public int Validate_Login(String Username, String Password)
{
SqlConnection con = new SqlConnection(@"User
id=sa;Password=Dotnetfunda;Server=VUYISWAVUYISWA;Database=Forum");
SqlCommand cmdselect = new SqlCommand();
cmdselect.CommandType = CommandType.StoredProcedure;
cmdselect.CommandText = "[dbo].[prcLoginv]";
cmdselect.Parameters.Add("@Username", SqlDbType.VarChar, 50).Value = Username;
cmdselect.Parameters.Add("@UPassword", SqlDbType.VarChar, 50).Value =
Password;
cmdselect.Parameters.Add("@OutRes", SqlDbType.Int, 4);
cmdselect.Parameters["@OutRes"].Direction = ParameterDirection.Output;
cmdselect.Connection = con;
int Results = 0;
try
{
con.Open();
cmdselect.ExecuteNonQuery();
Results = (int)cmdselect.Parameters["@OutRes"].Value;
}
catch (SqlException ex)
{
lblMessage.Text = ex.Message;
}
finally
{
cmdselect.Dispose();
if (con != null)
{
con.Close();
}
}
return Results;
}
As you can see this Function return an Integer, as we said before this will return
either a 1 which is equal to “Good” and other numbers will be “Bad”. The login Data
should be clean, no Duplicates should be there because this will break your
functionality. It might return the duplicates and the count might not match the if
statement that you will see later in this article. Double click you Button and add the
following code in the Click event of the Button.
19. protected void btnlogin_Click(object sender, EventArgs e)
{
int Results = 0;
if (txtUsername.Text != string.empty && txtPassword.Text != string.empty)
{
Results = Validate_Login(txtUsername.Text.trim(),
txtPassword.Text.trim());
if (Results == 1)
{
lblMessage.Text = "Login is Good, Send the User to another page or
enable controls";
}
else
{
lblMessage.Text = "Invalid Login";
lblMessage.ForeColor = System.Drawing.Color.Red;
//Dont Give too much information this might tell a hacker what is wrong in the
login
}
}
else
{
lblMessage.Text = "Please make sure that the username and the password is
Correct";
}
}
Now our code is ready for testing. Run your Application and enter an incorrect
password deliberately and see what message you see and when you enter the
correct login you will receive a message that says