【发布时间】:2018-01-06 10:13:15
【问题描述】:
我有 2 页,第一个(索引)是一个带有 2 个 TextForm 的表单,2 个信息是通过 POST 方法发送的。 在第二个页面(WebForm)中,点击更新时间按钮后,其他2项(FirstName和LastName)消失了,不明白为什么? 我应该怎么做才能“保留”这两个项目?
这些是所有页面:
index.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="HelloWorlds.Index" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="firstName" runat="server"></asp:TextBox>
<asp:TextBox ID="secondName" runat="server"></asp:TextBox>
<asp:Button ID="btn" runat="server" Text="GO!" PostBackUrl="~/WebForm.aspx" />
</div>
</form>
</body>
</html>
WebForm.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm.aspx.cs" Inherits="HelloWorlds.WebForm" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="item1" runat="server"></asp:TextBox>
<asp:Button ID="b1" runat="server" Text="Click Here!" OnClick="b1_Click"></asp:Button>
<br /> <br />
<asp:Label ID="labelFirstName" runat="server"></asp:Label>
<asp:Label ID="labelLastName" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
索引.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace HelloWorlds
{
public partial class Index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
WebForm.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace HelloWorlds
{
public partial class WebForm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DateTime actualDate = DateTime.Now;
item1.Text = actualDate.ToString();
string firstName = Request.Form["firstName"];
string lastName = Request.Form["secondName"];
if (firstName == "FirstName" && lastName == "SecondName") {
labelFirstName.Text = "Not Valid";
labelLastName.Text = "Not Valid";
}
else {
labelFirstName.Text = firstName;
labelLastName.Text = lastName;
}
}
protected void b1_Click(object sender, EventArgs e)
{
DateTime actualDate = DateTime.Now;
item1.Text = actualDate.ToString();
}
}
}
【问题讨论】:
-
你要明白web公司和windows窗体是不一样的。 Web 表单状态较少,因此当您单击按钮时,整个页面将再次加载,从而再次执行 page_load。所以下一个有效负载不会有
Request.Form["firstName"]和其他值。这就是为什么你会看到价值消失的原因。您需要将 page_load 的代码放在if(!IsPostBack)块中