将值传递到下一页

HL8*_*HL8 5 asp.net

我有登录页面,登录后我创建了一个会话变量来存储UserName.我已经使用此变量从Account表中使用AccountID,名称等检索此用户的信息,并使用标签(lblAccountID)返回页面上的AccountID.

我有一个"添加资金"按钮到此帐户,该按钮重定向到AddFunds.aspx页面

如何将AccountID传递到AddFunds.aspx页面,该页面将用于将详细信息插入到具有AccountID的Funds表中.

我不希望AccountID在AddFunds.aspx页面上可见.

Mur*_*aza 28

有多种方法可以实现这一目标.我可以简要介绍一下我们在日常编程生命周期中使用的4种类型.

请仔细阅读以下几点.

1个查询字符串.

FirstForm.aspx.cs

Response.Redirect(“SecondForm.aspx?Parameter=” + TextBox1.Text);
Run Code Online (Sandbox Code Playgroud)

SecondForm.aspx.cs

TextBox1.Text = Request. QueryString["Parameter"].ToString();
Run Code Online (Sandbox Code Playgroud)

当您传递整数类型的值或其他短参数时,这是最可靠的方法.如果您在通过查询字符串传递值时使用值中的任何特殊字符,则此方法更进一步,您必须在将值传递给它之前对该值进行编码下一页.所以我们的代码片段将是这样的:

FirstForm.aspx.cs

Response.Redirect(“SecondForm.aspx?Parameter=” + Server.UrlEncode(TextBox1.Text));
Run Code Online (Sandbox Code Playgroud)

SecondForm.aspx.cs

TextBox1.Text = Server.UrlDecode(Request.QueryString["Parameter"].ToString());
Run Code Online (Sandbox Code Playgroud)

2.通过上下文对象传递值

通过上下文对象传递值是另一种广泛使用的方法.

FirstForm.aspx.cs

TextBox1.Text = this.Context.Items["Parameter"].ToString();
Run Code Online (Sandbox Code Playgroud)

SecondForm.aspx.cs

this.Context.Items["Parameter"] = TextBox1.Text;
Server.Transfer(“SecondForm.aspx”, true);
Run Code Online (Sandbox Code Playgroud)

请注意,我们使用Server.Transfer而不是Response.Redirect导航到另一个页面.我们中的一些人也使用Session对象传递值.在该方法中,值存储在Session对象中,然后在第二页的Session对象中拉出.

3.将表单发布到另一页而不是PostBack

通过将页面发布到另一个表单来传递值的第三种方法.这是一个例子:

FirstForm.aspx.cs

private void Page_Load(object sender, System.EventArgs e)
{
buttonSubmit.Attributes.Add(“onclick”, “return PostPage();”);
}
Run Code Online (Sandbox Code Playgroud)

我们创建一个javascript函数来发布表单.

SecondForm.aspx.cs

function PostPage()
{
document.Form1.action = “SecondForm.aspx”;
document.Form1.method = “POST”;
document.Form1.submit();
}
TextBox1.Text = Request.Form["TextBox1"].ToString();
Run Code Online (Sandbox Code Playgroud)

在这里,我们将表单发布到另一个页面而不是自己.您可能会使用此方法在第二页中获取viewstate无效或错误.要处理这个错误就是放EnableViewStateMac=false

另一种方法是为跨页回发添加控制的PostBackURL属性

在ASP.NET 2.0中,Microsoft通过为跨页回发添加控件的PostBackURL属性来解决此问题.实现是设置一个控制属性的问题,你就完成了.

FirstForm.aspx.cs

<asp:Button id=buttonPassValue style=”Z-INDEX: 102? runat=”server” Text=”Button”         PostBackUrl=”~/SecondForm.aspx”></asp:Button>
Run Code Online (Sandbox Code Playgroud)

SecondForm.aspx.cs

TextBox1.Text = Request.Form["TextBox1"].ToString();
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,我们分配了按钮的PostBackUrl属性,我们可以确定它将发布到的页面而不是它自己.在下一页中,我们可以使用Request对象访问上一页的所有控件.

您还可以使用PreviousPage类访问上一页的控件,而不是使用经典的Request对象.

SecondForm.aspx

TextBox textBoxTemp = (TextBox) PreviousPage.FindControl(“TextBox1?);
TextBox1.Text = textBoxTemp.Text;
Run Code Online (Sandbox Code Playgroud)

正如您所注意到的,这也是在页面之间传递值的简单而干净的实现.

参考:" 如何:在ASP.NET网页之间传递值 "