2011-06-25 107 views
0

我想在用戶瀏覽頁面時傳遞一個int值。超鏈接並跨頁傳遞變量

我有這樣的:

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

讓我們假設,我想5號傳遞到其他頁面。我怎麼做?

回答

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而不是超鏈接:

<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屬性是強類型的,即是默認的類型不只是網頁

+0

oooh好..你把它放在網址中..我忘了你能做到這一點! – Matrix001

+0

@ Matrix001:我還添加了更多有用的代碼 – abatishchev

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