Reputation: 21248
I'm working on an application "guess the number". If the user has used all the guesses, a button shows up (New game) and if the user clicks it the game (of course) starts over.
The problem is that when clicked, the form gets posted and an error message is shown because the input field is empty (validation). I just can't figure out why the form gets posted. The only thing I have inside the code when the New game button gets clicked is a line for resetting the session?
Below is the code from my code-behind file. It's alot of code because I didn't know what I could remove without ruins the possibility of understanding the cause of the problem.
Code behind:
private SecretNumber guessNr = null;
private SecretNumber guessSession
{
get { return Session["guessSession"] as SecretNumber; }
set { Session["guessSession"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnCheckNr_Click(object sender, EventArgs e) {
if (!Page.IsValid) {
return;
}
else {
if (guessSession == null){
guessSession = new SecretNumber();
}
guessNr = guessSession;
infoToUser.Visible = true;
string history = "";
foreach (var guesses in guessNr.PreviousGuesses) {
history += "[" + guesses.ToString() + "] ";
}
var guessedNr = int.Parse(inputBox.Text);
var result = (int)guessNr.MakeGuess(guessedNr);
guessHistory.Text = history;
lastGuess.Text = "[" + guessedNr.ToString() + "]";
switch (result){
case 1:
messageToUser.Text = " The number is too low.";
break;
case 2:
messageToUser.Text = " The number is too high.";
break;
case 3:
messageToUser.Text = String.Format(" Congratulations! You did it on {0} tries!", guessNr.Count);
btnCheckNr.Enabled = false;
inputBox.Enabled = false;
newGame.Visible = true;
break;
case 4:
messageToUser.Text = String.Format("" Game Over. The number was: {0}"", guessNr.Number);
btnCheckNr.Enabled = false;
inputBox.Enabled = false;
newGame.Visible = true;
break;
}
}
}
protected void btnNewGame_Click(object sender, EventArgs e) {
Session.Abandon();
}
Upvotes: 0
Views: 64
Reputation: 7619
I'm guessing you have some client side validation kicking off when the button is clicked because it's firing the default validation script.
In which case you should just be able to add this attribute to the new game button:
CausesValidation="false"
Upvotes: 1