2012-05-11 66 views
0

我試圖做一個簡單的網站,將產生2個數字,然後用戶將需要回答另外的這些數字2的正確的結果..價值在頁面生命週期中發生變化?

這是我的ASPX:

<div id="questionContainer"> 
    <asp:UpdatePanel ID="UpdatePanel1" runat="server"> 
       <ContentTemplate> 
     <div id="firstNumber"> 
      <%=firstNum %> 
     </div> 
     <div id="operator"> 
      <%=operatorString %> 
     </div> 
     <div id="secondNumber"> 
      <%=secondNum %> 
     </div> 
     <div id="answerWrapper"> 

        <input type="text" id="answer" name="answer" placeholder="your answer" /> 

      <asp:Button runat="server" ID="submit" name="submit" OnClick="AnswerQuestion" Text="Answer" /> 
       <input type="hidden" name="op" id="op" value="1" /> 
      <div id="error"> 
       <%=textForUser %> 
      </div> 
      </ContentTemplate> 
      </asp:UpdatePanel> 
     </div> 

這是後臺代碼:

protected static int firstNum; 
    protected static int secondNum; 
    protected bool operatorTrueOrFalse = true; 
    protected string operatorString = "+"; 
    protected GameLogic gl; 
    protected static int answer; 
    protected bool isItTrue; 
    protected int userAnswer; 
    protected string textForUser ="hello"; 
    protected string op; 

    protected void Page_Load(object sender, EventArgs e) 
    { 



     if (Page.IsPostBack || op == "1") // if solved X or null. 
     { 
      gl = new GameLogic(); 
      firstNum = gl.GenerateNumber(4); 

      secondNum = gl.GenerateNumber(4); 

      answer = gl.SolveFor(firstNum, secondNum, operatorString); 
     } 


    } 

    public void AnswerQuestion(object sender, EventArgs e) 
    { 
     if (Request["answer"] != null) 
     { 
      userAnswer = int.Parse(Request["answer"]); 

     } 
     else 
     { 
      textForUser = "You need to type something"; 
     } 


     if (answer == userAnswer) 
     { // user has answered correctly. 
      isItTrue = true; 
      textForUser = "very good"; 
      op = "1"; 
     } 
     else 
     {// user has answered in - correctly. 
      isItTrue = false; 
      textForUser = "you are wrong"; 
      op = "0"; 
     } 
    } 

的問題是,我注意到,每一次我嘗試回答在文本框中的問題,變化的數字。它就像我不能回答正確的問題。

回答

3

您正在重新生成一個新的數字對似乎回發。基本上,邏輯應該是這樣的話,如果你打算住在同一頁面上反覆,只是發佈答案:

1) Is this a postback? 
    -> No: Generate a new value and store it in ViewState. Hold onto this value. 
    -> Yes: Do we have a stored answer value in ViewState? 
     -> No: Error? Something has gone wrong. 
     -> Yes: Fetch that Value and hold on to it 
2) On Button Click, Is the answer you entered the same as the generated value? 
    -> No: Show Error 
    -> Yes: Show Success, Then generate a new value and store it in ViewState 

你的算法似乎只在後要產生一個新的答案對背部和上每回發。

+0

+1一個不錯的路線圖。對讀者有幫助。 – Jeremy

3

問題是,您正在使用靜態變量。這些是跨所有請求共享。不要爲此使用靜態變量,而是將它們存儲在別處(f.e.Session,ViewState,Hiddenfield,...)。

Nine Options for Managing Persistent User State in Your ASP.NET Application

  • 應用
  • 餅乾
  • 表單提交/隱藏的表單字段
  • 查詢字符串
  • 會議
  • 新州集裝箱在ASP.NET
  • 緩存
  • 語境
  • 的ViewState
  • 的Web.config和Machine.config中的文件

...當然數據庫。