开发者

Hyperlink and passing variables across pages

I want to pass an int as the user navigates acro开发者_StackOverflow中文版ss the pages.

I have got this:

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

Lets suppose that i want to pass the number 5 to the other page. How do i do that?


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

You can secure such operation. Use LinkButton instead of HyperLink on first page:

<asp:LinkButton runat="server" PostBackUrl="~/Question.aspx?x=5">Question #5</asp:LinkButton>

and then on second:

<%@ PreviousPageType VirtualPath="~/Default.aspx" %>

if (this.PreviousPage != null && this.PreviousPage.IsValid)
{
    // do the same
}

Note that PreviousPage property is strongly typed, i.e. is type of Default not just Page


You can also use Session variables to set a value on one page:

class Default : Page
{
    // ...other code

    Session["myValue"] = "5";
}

And then pick it up on the receiver page with:

class TargetPage : Page
{
    // other code...
    int x; 
    try {
        x = int.Parse(Session["myValue"]);
    } catch {}

    // do something with x
}

The good thing about Session variables is that you can use any data type/object, and it's hidden from the user, i.e. not visible in the URL.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜