2015-08-23 31 views
0

我正在爲我的網頁在c#asp.net的熱門計數器工作。我試圖使用會話狀態從一個Web窗體顯示命中計數器的字符串值,並將其放置在另一個Web窗體中。它可以工作,但只有在我來回瀏覽鏈接以測試增量之後,否則第一次加載頁面時,計數器計數不會顯示在標籤上。任何線索我怎麼能解決這個問題,我想過使用cookie。但即使第一次訪問者來到我的頁面,我的計數器仍然無法正確顯示。我非常渴望解決這個問題。會話狀態值沒有出現在我的標籤中

這是我嘗試使用的會話狀態碼。

形式,是想顯示標籤

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Data; 
using System.Data.SqlClient; 
using System.Web.Configuration; 

    namespace VideoWebsite 
    { 
    public partial class WebForm2 : System.Web.UI.Page 
    { 
     protected void Page_Load(object sender, EventArgs e) 
     { 

     if (!Page.IsPostBack) 
     { 
       string field1 = (string)(Session["field1"]); 
       Label1.Text = field1; 
     } 

     } 

    } 

形式,其中我想,當因爲會話變量第一次訪問從

protected void Page_Load(object sender, EventArgs e) 
    { 
     SqlConnection conn; 
     SqlCommand cmd; 

     using (conn) 
     { 
      //open the connection 
      conn.Open(); 
      //send the query and store the results in a sqldatareader 
      SqlDataReader rdr = cmd.ExecuteReader(); 


      if (rdr.Read()) 
      { 
       //set the text of our label to the current # of hits 
       lblHits.Text = "Default Page Hits - " + 
       rdr["Hits"].ToString(); 
      } 

      Session["field1"] = rdr["Hits"].ToString(); 

     } 
    } 

回答

1

它不會顯示獲取會話狀態值尚不存在。您只是在第二個Web表單中創建它。

您應該將讀取數據庫信息的代碼移動到global.asax中會話創建的事件處理程序。

對不起,我無法發佈代碼,我從Android應用程序打字。

protected void Session_Start(object sender, EventArgs e) 

       { 

         // Your Hits read code goes here 

       } 
+0

我對會話狀態的工作方式不太瞭解,任何方式我都可以解決這個問題,所以即使我是第一次訪問網頁,它也會顯示。 –

+0

確實,會話狀態是在應用程序的第一次訪問時創建的。但是,該會話變量,您只是在訪問第二個Web表單時創建它。在此之前它不存在並且將返回null。 –

+0

我明白了。但問題是我需要的價值是我的另一種形式,會話狀態的整個點是將該值移動到另一個表單,但我想要爲首次訪問者顯示點擊數。我想過用cookie來解決這個問題。但第一次訪問者或刪除他們的cookies的人仍然會有這個問題。任何簡單的想法我怎麼能解決這個問題? –