Part 55 - Cross Page Postback Part 56 - Cross Page Postback Strongly Typed Reference
Part 55 - Cross Page Postback Part 56 - Cross Page Postback Strongly Typed Reference
In general, the members of one Web form are unavailable from a subsequently
displayed Web form. However, when navigating between Web forms using the Transfer or
Execute method, data can be retrieve from the previous Web form using Context.Handler
object.
WebForm1.aspx.cs Code:
protected void Button1_Click(object sender, EventArgs e)
{
Server.Transfer("~/WebForm2.aspx");
}
public string Name
{
get
{
return txtName.Text;
}
}
public string Email
{
get
{
return txtEmail.Text;
}
}
WebForm2.aspx.cs Code:
//On postback Context.Handler returns WebForm2
if (!IsPostBack)
{
Page lastpage = (Page)Context.Handler;
if (lastpage is WebForm1)
{
//Use FindControl() if public properties does not exist on the
//previous page(WebForm1). FindControl() may cause
//NullRefernceExceptions due to mis-spelled conrol Id's
//lblName.Text = ((TextBox)lastpage.FindControl("txtName")).Text;
//lblEmail.Text = ((TextBox)lastpage.FindControl("txtEmail")).Text;
//Using public properties can eliminate NullRefernceExceptions
lblName.Text = ((WebForm1)lastpage).Name;
lblEmail.Text = ((WebForm1)lastpage).Email;
}
}
Or
&(ampersand) is encoded as %26, so use, Replace() function to replace & with %26
Response.Redirect("WebForm2.aspx?UserName=" + txtName.Text.Replace("&", "%26") +
"&UserEmail=" + txtEmail.Text.Replace("&", "%26"));
WebForm1.aspx HTML: We want to send Name and Email, that user enters on
WebForm1.aspx to WebForm2.aspx using query strings.
<div style="font-family: Arial">
<table>
<tr>
<td colspan="2">
<h1>
This is WebForm1</h1>
</td>
</tr>
<tr>
<td>
<b>Name</b>
</td>
<td>
:<asp:TextBox ID="txtName" runat="server">
</asp:TextBox>
</td>
</tr>
<tr>
<td>
<b>Email</b>
</td>
<td>
:<asp:TextBox ID="txtEmail" runat="server">
</asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="btnSendData" runat="server"
Text="Go to WebForm2" onclick="btnSendData_Click" />
</td>
</tr>
</table>
</div>
WebForm1.aspx.cs
protected void btnSendData_Click(object sender, EventArgs e)
{
//Using Server.UrlEncode to encode &(ampersand)
//Response.Redirect("WebForm2.aspx?UserName=" + Server.UrlEncode(txtName.Text)
+
// "&UserEmail=" + Server.UrlEncode(txtEmail.Text));
//Using String.Replace() function to replace &(ampersand) with %26
Response.Redirect("WebForm2.aspx?UserName=" + txtName.Text.Replace("&", "%26")
+
"&UserEmail=" + txtEmail.Text.Replace("&", "%26"));
}
WebForm2.aspx HTML:
<div style="font-family: Arial">
<table>
<tr>
<td colspan="2">
<h1>This is WebForm2</h1>
</td>
</tr>
<tr>
<td>
<b>Name</b>
</td>
<td>
:<asp:Label ID="lblName" runat="server">
</asp:Label>
</td>
</tr>
<tr>
<td>
<b>Email</b>
</td>
<td>
:<asp:Label ID="lblEmail" runat="server">
</asp:Label>
</td>
</tr>
</table>
</div>
WebForm2.aspx.cs Code:
protected void Page_Load(object sender, EventArgs e)
{
// Read the QueryString values
lblName.Text = Request.QueryString["UserName"];
lblEmail.Text = Request.QueryString["UserEmail"];
}
In this video, we will discuss about the asp.net session state mode -
StateServer.Asp.net session state mode can have any of the following 4 values. Asp.net
session state mode is set in web.config file.
1. Off - Disables session state for the entire application.
2. InProc - Discussed in Part 64
3. StateServer - Will be discussed in this session.
The following session state modes will be discussed in a later video session.
4. SQLServer
5. Custom
When the session state mode is set to StateServer, the session state variables are
stored in a process, called as asp.net state service. This process is different from the asp.net
worker process. The asp.net state service can be present on a web server or a dedicated
machine.
When the session state mode is set to SQLServer, the session state variables are stored
in a SQLServer database.
Note: If you use integrated security(windows authentication), you might get an error
stating "Failed to login to session state SQL server for user 'IIS APPPOOL\ASP.NET v4.0'.".
To resolve this error
a) click Start > Type Run > Press Enter
b) Type inetmgr > Press Enter
c) Expand IIIS and Click on Application Pools.
d) Right click on ASP.NET v4.0 and select Advanced settings
e) Change Process Model > Identity to LocalSystem and Click OK
Note:
Web Garden - Web application deployed on a server with multiple processors
Web Farm - Web application deployed on multiple server
Suggested Videos
Part 64 - Inporc asp.net session state mode management
Part 65 - StateServer asp.net session state mode management
Part 66 - SQLServer asp.net session state mode management
Part - 67
1. Application State variables are available across all pages and across all sessions.
Application State variables are like multi-user global data.
3. Application State variables are cleared, only when the process hosting the application
is restarted, that is when the application ends.
4. Application State variables are not shared across a Web Farm or a Web Garden.
5. Application state variables are not thread safe. Lock and Unlock methods of the
application class must be used to protect against race conditions, deadlocks, and access
violations.
Application.Lock();
Application["GlobalVariable"] = (int)Application["GlobalVariable"] + 1;
Application.UnLock();
Please Note: In this example, we are using application state variables to send data from one
web form to another. If the requirement, is just to send data from webform to another, you
should consider other alternatives.
6. Use application state variables only, when the variables need to have global access
and when you need them for entire time, during the life time of an application. Cache
object, can be used, as an alternative, if you need to have global access for a certain
duration.
Forms authentication using user names list in web.config - Part 90
Suggested Videos
Part 87 - Windows authentication
Part 88 - Windows authentication and authorization
Part 89 - Windows authentication and folder level authorization
Anonymous authentication is fine for web sites that contain public informationthat
every one can see. We discussed about Anonymous authentication in
Part 85 - Anonymous authentication
Part 86 - Anonymous authentication and impersonation
Windows authentication is used for intranet web applications, where the users are part
of a windows domain-based network. We discussed about Windows authentication in Parts
87, 88 and 89.
Welcome.aspx HTML:
<h1>Welcome Page</h1>
Login.aspx HTML:
<div style="font-family:Arial">
<table style="border: 1px solid black">
<tr>
<td colspan="2">
<b>Login</b>
</td>
</tr>
<tr>
<td>
User Name
</td>
<td>
:<asp:TextBox ID="txtUserName" runat="server">
</asp:TextBox>
</td>
</tr>
<tr>
<td>
Password
</td>
<td>
:<asp:TextBox ID="txtPassword" TextMode="Password" runat="server">
</asp:TextBox>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnLogin" runat="server" Text="Login" />
</td>
</tr>
</table>
<br />
<a href="Registration/Register.aspx">Click here to register</a>
if you do not have a user name and password.
</div>
Register.aspx HTML:
<h1>Registration Page</h1>
If you run the application now, we will be able to navigate to any page, just by changing
the name of the page in the address bar. We are not logged in, but we are still able to
access all the pages in the application.
<authorization>
<deny users="?" />
</authorization>
The description of the attributes
loginUrl - The URL of the login Page
timeout - Specifies the number of minutes the authentication cookie persists on the clients’s
computer. The default is 30 minutes.
defaultUrl - The url the user will be redirected after authentication
Protection - Specifies the protection for authentication cookie stored on the clients’s
computer. The default is All, which performs encryption and data validation. Other possible
settings are Encryption, Validation, and None.
Double click the login button on the Login.aspx page. Copy and paste the following code
in the button click event handler.
// Authenticate againts the list stored in web.config
if (FormsAuthentication.Authenticate(txtUserName.Text, txtPassword.Text))
{
// Create the authentication cookie and redirect the user to welcome page
FormsAuthentication.RedirectFromLoginPage(txtUserName.Text,
chkBoxRememberMe.Checked);
}
else
{
lblMessage.Text = "Invalid UserName and/or password";
}
2. At the moment, users are not able to access Register.aspx page, if they are not logged in.
If a user does not have user name and password, he should be able to register himself using
Register.aspx page. In a later video session, we will discuss about this.
In this code sample, we have used validation controls and ADO.NET. If you have not
watched the videos on validation controls and ADO.NET, I would strongly encourage you to
do so, before continuing with this session.
Please watch Part - 90, before proceeding. In Part - 90, we have discussed the basics of
Forms authentication. One of the problems, with the example in Part 90, is that, we are not
able to navigate to Registration/Register.aspx page if we are not logged in.
To solve this issue, add another web.config file to the "Registration" folder, and specify the
authorization element to allow all users.
<authorization>
<allow users="*"/>
</authorization>
At this point, without logging into the application, users should be able to navigate to
Registration/Register.aspx page.
Copy and Paste the following code in the "Register" button click event.
// If the Page has no validation errors
if (Page.IsValid)
{
// Read the connection string from web.config.
// ConfigurationManager class is in System.Configuration namespace
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
// SqlConnection is in System.Data.SqlClient namespace
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("spRegisterUser", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(username);
cmd.Parameters.Add(password);
cmd.Parameters.Add(email);
con.Open();
int ReturnCode = (int)cmd.ExecuteScalar();
if (ReturnCode == -1)
{
lblMessage.Text = "User Name already in use, please choose another user name";
}
else
{
Response.Redirect("~/Login.aspx");
}
}
}
Run the application. Fill in the required details, and click "Register" button. The user
should be added to the database. In the next video session, we will discuss about,
authenticating with the credentials we stored in the database.