0

I am writing my first application in razor and finding it fun and addictive. I have found answers on this site really useful to sort out many errors in my code. So thank you to the community already. I have nearly finished my program, which is a quiz website that allows users to upload their own questions and answers to a database.

I have encountered a problem comparing strings where one variable is passed via a html form using the get method. If the user answers the correct answer, my page shows that both variables (strings) are the same, but when comparing them, my bool still returns false.

I am sorry if this is obvious, or has already been asked before. If so, could you redirect me to a source that would explain what I am doing wrong. Many thanks Here is the part of the code that doesn't work

@{
var uAns = " ";
var cAns = "x";
bool? anBool = null; // should set to true if user answer is correct

if (!Request.QueryString["uAnswer"].IsEmpty())
{
    uAns = Request.QueryString["uAnswer"];
}    
    if (String.Equals(uAns, cAns, StringComparison.OrdinalIgnoreCase) == true)
            {
                anBool = true;
            }
            else
            {
                anBool = false;
            }
}


<!DOCTYPE html>

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        <form action="" method="get">
      <p><label for="uAnswer">Answer:</label>
        <input type="text" name="uAnswer" value=" "/>
      </p>

      <p><input type="submit"/></p>
      </form>
        uAns = @uAns
        cAns = @cAns
        <p>anBool = @anBool</p> // why is this always false ?? :-(
    </body>
</html>
  • Just to update - if I change my form value to: value="@Request.QueryString["uAnswer"]" my form works as it should. However is the value reads: value="@uAns" My bool returns false. Since: uAns = Request.QueryString["uAnswer"] why does one work and not the other??? – Ben Pearson Apr 13 '15 at 18:02

1 Answers1

0

The default value of your input field is a single space rather than an empty string. If you simply add "x" to the input field and submit the form (without deleting the space) the query string will appear as ?uAnswer=+x instead of the desired ?uAnswer=x.

If you replace:

<input type="text" name="uAnswer" value=" "/>

with

<input type="text" name="uAnswer" value=""/>

everything should work properly.

Rob Purcell
  • 1,285
  • 1
  • 9
  • 19