17,740
社区成员
发帖
与我相关
我的任务
分享
public partial class testpage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
Session["aafasfdaf"] = 1;
}
protected void Button1_Click(object sender, EventArgs e)
{
this.Session["username"] = this.username.Text;
this.Server.Transfer("nextpage.aspx", true);
}
}
这里,假设这个页面是整个网站的默认起始页面,当初次访问这个页面时先往 Session 集合随便写一个值,保证 asp.net 系统之后要稳定维持这个会话 SessionID,这样在 button 按钮的回发事件处理中再重定向到其它页面,才能确保在其它页面能取 Session["username"] 单元的值。public partial class testpage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
this.Session["username"] = this.username.Text;
this.Response.Redirect("nextpage.aspx");
}
}
或者 public partial class testpage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
this.Session["username"] = this.username.Text;
this.Server.Transfer("nextpage.aspx", true);
}
}
等等方式。
假设你要脱离开 asp.net 编程机制,那么你就应该知道 Request.Form[key] 这里的 key 并不保证是什么服务器 TextBox 控件的 ID,而是控件的 UniqueID 属性。理解这个机制,那么按照 asp.net 主流编程范式来写代码比较省力,这样用不着注意那么多坑。<form id="form1" runat="server" method="post" action="test1show.aspx">
另外一个页面使用Request.Form["username"]获取前面页面TextBox的值username.Text
。这里的问题,在于那个教你写 Requst.Form[.....] 的人把你带到“沟里”了。对于非常简单、页面上除了一层最简单的几个控件就什么都没有的那种页面,你可以写 Request.Form["username"]。但是稍微复杂一点的页面——正规的页面——你应该写username.Text
来读写这个文本控件的 Text属性值。这就好像一个业余拳击手还没有学好基本功就学习毫无防护和套路的街头肉搏,那么你学的拳击师傅肯定不是正轨训练出来的师傅。username.Text
来看获取提交的值,而使用Request.Form["username"]
并不保证能读取到那个文本框,因为文本框输出的客户端 html element 的 name 属性值是不确定的,例如可能是 ctl0_ctl1_name 而不保证就是 name。