2011-10-22 189 views
0

只是一個小問題,因爲我找不到解決我的問題的答案。返回值來自會話

我有一個ASP頁面,它將輸入發送到數據庫,然後創建一個會話。我想知道如何在的另一個 aspx頁面上返回該會話中的某個值。

page1.aspx.cs [創建會話]

public partial class new_questionnaire : System.Web.UI.Page 
    { 
     OscarSQL c; 

      protected void Page_Load(object sender, EventArgs e) 
      { 
       c = new OscarSQL(); 
      } // End Page_Load 

      ////// Button Method //////   
      protected void NewQnrButton_Click(object sender, EventArgs e) 
      { 
       // Check if the input fields are empty. 
       if (QuestionnaireName.Text == "" || CustomerID.Text == "" || NumberOfQuest.Text == "") 
       { 
        Error.Text = "Please enter a name for your questionnaire."; 
       } 
       // Parse input values to OscarSQL. 
       else 
       { 

        int testRet = c.InsertQuestionnaire(QuestionnaireName.Text, Int32.Parse(CustomerID.Text), Int32.Parse(NumberOfQuest.Text)); 
        Session["Questionnaire"] = testRet; 
        Confirm.Text = "Your questionnaire has been named " + QuestionnaireName.Text; 
        Response.Redirect("~/add_questions.aspx"); 
       } 

      } // End NewQNRButton_Click 

     } // End new_questionnaire 

Page2.aspx.cs [想價值在這裏解析]

namespace OSQARv0._1 
{ 
    public partial class WebForm2 : System.Web.UI.Page 
    { 
     protected void Page_Load(object sender, EventArgs e) 
     { 
      //ReturnQnrName.Text here? 

     } 
    } 
} 

我想從價值QuestionnaireName.Text Page1第2頁

回答

4

您沒有將QuestionnaireName.Text放入Page1的會話中,您輸入了一個整數。如果您需要實際的文本屬性,將其寫入會議

Session["theText"] = QuestionnaireName.Text; 

然後你可以檢索

string text = (string)Session["theText"]; 

這揭示了一些有關會議。對象存儲類型爲object,您需要在使用前將它們轉換爲正確的類型。例如,檢索你把會議的整數,你會寫

int questionnaire = (int)Session["Questionnaire"]; 
+0

謝謝,這對我來說是乾淨的解決方案。 – HGomez90

1

您正在做

Session["Questionnaire"] = testRet; 

On Page1。 Page2上你可以做:

protected void Page_Load(object sender, EventArgs e) 
{ 
    string questionnaire = Session["Questionnaire"] as string; 
    if(!string.IsNullOrEmpty(questionnaire)) 
    ReturnQnrName.Text =questionnaire ; 

} 

注意 只是意識到你把一個int會話中的,但你似乎想要存儲在會話文本和檢索。原理是一樣的。

+0

爲什麼不:'串問卷=會話[「問卷」];' – Kakashi

+2

@Kakashi因爲它是不好的做法。 'Session [「Questionnaire」]'中的值可以在您有機會分配之前刪除。考慮InProcess會話狀態。您的應用程序池可以隨時回收。 – Icarus

+0

我也試過這種方法。謝謝。 未來可能會使用它,因爲它有更多擴展空間=] – HGomez90

0

只是這樣做:

string question = Session["Questionnaire"]; 

    if(question=="") 
    { 
     //No Value 
    } 
else 
{ 
    ReturnQnrName.Text = question; 
} 

問候

0

您可以使用Session [ 「QuestionnaireName」] = QuestionnaireName.Text;

在第二頁,你可以retrive值象下面

   string QuestionnarireName; 
       if (Session["QuestionnaireName"] != null) 
       { 
        QuestionnarireName = Session["QuestionnaireName"].ToString(); 

       } 

否則你可以把在ViewState中也。 Passing data between forms