Search code examples
c#asp.net-coreblazorpage-lifecycle

Blazor component not executing the NavManager.NavigateTo


I have a strange occurrence, I have a login screen, which takes the inputs of two text box's UserName and password, it checks to see if the user has an account as brings back the user id..

enter image description here

But when i call the method from a button click, for some strange reason the page refreshes and this query string pops up on my bar enter image description here

And then the code begins to execute... Also it does not navigate the page i am requesting...

My data that is bought back is fine, but im clearly missing understanding how the life cycles work.. Any suggestions?

My component

<html>
<body>
    <div class="container">
        <div class="header-text">
            &nbsp;&nbsp;&nbsp;<img style="height:200px; width:200px" class="header-text-logo" src="/logo/WebbiSkoolsLogo.jpg" alt="logo">
            <p class="header-text-description">Student Login</p>
        </div>
        <form>
            <input type="text"
                   placeholder="Username"
                   name="username"
                   id="username"
                   @oninput="@((e) => { Username = (string)e.Value; })"
                   autofocus>
            <input type="password"
                   name="password"
                   id="password"
                   @oninput="@((e) => { Password = (string)e.Value; })"
                   placeholder="Password"
                   required>
            <button @onclick="ValidateUser" style="cursor:pointer" type="submit" name="login">Login</button>
            <button @onclick="AddUserTest" style="cursor:pointer" type="submit" name="login">Add User</button>
            <div class="text-lg-center">
                @*<p style="color:red"><h1>@Errors</h1></p>*@
            </div>
        </form>
    </div>
</body>
</html>

Component Code

@code {
    private string Username { get; set; }
    private string Password { get; set; }
    private string Errors = string.Empty;
    private int UserId = 0;
    public bool IsShow { get; set; } = false;

    private void ValidateUser()
    {

        string user = Username;
        string pass = Password;

        UserId =  TryLogin(user, pass);

        if (UserId != 0)
        {
            NavManager.NavigateTo("QuizEdit");
        }
        else
        {
            Errors = "Failed to log in";
        }

    }

Code behind

public int TryLogin(string user, string pass)
        {
            connectionString = Settings.Value.ConnectionString;
            Login login = new Login();
            UserId =  login.GetUserIdByUsernameAndPassword(user, pass, connectionString);
            return UserId;
        }

And my login checking

public int GetUserIdByUsernameAndPassword(string username, string password, string connectionString)
        {
            // this is the value we will return
            int userId = 0;
            
            
            SqlConnection con = new SqlConnection(connectionString);
            using (SqlCommand cmd = new SqlCommand("SELECT UserId, Password, Guid FROM [UserDetails] WHERE username=@username", con))
            {
                cmd.Parameters.AddWithValue("@username", username);
                con.Open();
                SqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    // dr.Read() = we found user(s) with matching username!

                    int dbUserId = Convert.ToInt32(dr["UserId"]);
                    string dbPassword = Convert.ToString(dr["Password"]);
                    string dbUserGuid = Convert.ToString(dr["Guid"]);

                    // Now we hash the UserGuid from the database with the password we wan't to check
                    // In the same way as when we saved it to the database in the first place. (see AddUser() function)
                    string hashedPassword = Security.HashSHA1(password + dbUserGuid);

                    // if its correct password the result of the hash is the same as in the database
                    if (dbPassword == hashedPassword)
                    {
                        // The password is correct
                        userId = dbUserId;
                    }
                }
                con.Close();
            }

            // Return the user id which is 0 if we did not found a user.
            return userId;
        }

Solution

  • The issue is that you use "submit" buttons on a form. When you click on each of them an HTTP post request takes place. But this was not your intention. You want to call ValidateUser and AddUserTest, but instead you post to the server, a meaningless post request. You should instead use the input element with type="button" or button element