超链接和跨页面传递变量

时间:2011-06-25 10:01:49

标签: c# .net asp.net hyperlink

我希望在用户浏览页面时传递一个int。

我有这个:

Hyperlink q = new HyperLink();
q.Text = ThreadName;
q.NavigateUrl = "AnswerQuestion.aspx";

假设我想将数字5传递给另一页。我该怎么做?

2 个答案:

答案 0 :(得分:4)

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
    }
}

您可以保护此类操作。在第一页上使用LinkBut​​ton而不是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属性是强类型的,即默认类型不仅仅是Page

答案 1 :(得分:0)

您还可以使用Session variables在一个页面上设置值:

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中不可见。

相关问题