Another approach for saving the data for the user is the view state, as described in this tutorial elsewhere, the view state allows ASP.NET to resize form fields on each post back on the server, ensuring that That's when the user hits the submit button, the form is not automatically cleared. All this happens automatically, until you turn it off, but you can actually use View State for your own purposes. Please keep in mind that while cookies and sessions can be accessed from all your pages on your website, view State values are not made between pages. Here is a simple example of using View State to move values between post backs:
Demo.aspx
<%@ 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 runat="server">
<title>ViewState</title>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox runat="server" id="NameField" />
<asp:Button runat="server" id="SubmitForm" onclick="SubmitForm_Click" text="Submit & set name" />
<asp:Button runat="server" id="RefreshPage" text="Just submit" />
<br /><br />
Name retrieved from ViewState: <asp:Label runat="server" id="NameLabel" />
</form>
</body>
</html>
using System;
using System.Data;
using System.Web;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(ViewState["NameOfUser"] != null)
NameLabel.Text = ViewState["NameOfUser"].ToString();
else
NameLabel.Text = "Not set yet...";
}
protected void SubmitForm_Click(object sender, EventArgs e)
{
ViewState["NameOfUser"] = NameField.Text;
NameLabel.Text = NameField.Text;
}
}
Try to run the project, enter your name in the text box and press the first button the name will be saved in the view test and also set to the label. There is no magic at all. Now press the second button. It does not really do anything, it only posts back to the server.
0 comments:
Post a Comment