如何解决超链接和跨页面传递变量
| 我想在用户浏览页面时传递int值。 我有这个:Hyperlink q = new HyperLink();
q.Text = ThreadName;
q.NavigateUrl = \"AnswerQuestion.aspx\";
让我们假设我想将数字5传递给另一页。我怎么做?
解决方法
class Default : Page
{
q.NavigateUrl = \"AnswerQuestion.aspx?x=5\";
}
class AnswerQuestion : Page
{
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
string x = this.Request.QueryString[\"x\"];
int i;
if (!Int32.TryParse(x,out i))
throw new Exception(\"Can\'t parse x as int\");
// then use i
}
}
您可以确保这种操作。在第一页上使用LinkButton代替HyperLink:
<asp:LinkButton runat=\"server\" PostBackUrl=\"~/Question.aspx?x=5\">Question #5</asp:LinkButton>
然后第二个:
<%@ PreviousPageType VirtualPath=\"~/Default.aspx\" %>
if (this.PreviousPage != null && this.PreviousPage.IsValid)
{
// do the same
}
请注意,PreviousPage属性是强类型的,即Default类型不仅是Page类型
, 您还可以使用Session变量在一页上设置值:
class Default : Page
{
// ...other code
Session[\"myValue\"] = \"5\";
}
然后使用以下命令在接收器页面上将其拾取:
class TargetPage : Page
{
// other code...
int x;
try {
x = int.Parse(Session[\"myValue\"]);
} catch {}
// do something with x
}
Session
变量的好处是您可以使用任何数据类型/对象,并且对用户而言是隐藏的,即在URL中不可见。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。