簡體   English   中英

會話狀態值未出現在我的標簽中

[英]Session state value doesn't appear in my label

我正在為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(); 

        }
   }

由於該會話變量尚不存在,因此在首次訪問時不會顯示。 您僅在第二個Web表單中創建它。

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

抱歉,我無法發布代碼,我是在Android應用中輸入內容。

protected void Session_Start(object sender, EventArgs e)

       {

         // Your Hits read code goes here

       }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM