@page "/login"
@using BlazorWebAppNew.Data
@inject IJSRuntime JSRuntime
@inject UserDataContext dataContext
<PageTitle>Login</PageTitle>
<div class="container mt-5">
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card">
<div class="card-header">
<h6 class="card-title">Please log in</h6>
</div>
<div class="card-body">
<EditForm Model="@loginModel" OnValidSubmit="HandleLogin" FormName="LoginForm">
<DataAnnotationsValidator />
<ValidationSummary />
<div class="form-group mb-2">
<label for="email">Email:</label>
<InputText id="email" @bind-Value="loginModel.Email"></InputText>
</div>
<div class="form-group mb-2">
<label for="password">Password:</label>
<InputText id="password" type="password" @bind-Value="loginModel.Password"></InputText>
</div>
<button type="submit" class="btn btn-primary">Login</button>
</EditForm>
</div>
</div>
</div>
</div>
</div>
@code {
private LoginModel loginModel = new LoginModel();
private async Task HandleLogin()
{
Console.WriteLine($"Email: {loginModel.Email}, Password: {loginModel.Password}");
var user = await dataContext.Users
.FirstOrDefaultAsync(u => u.Email == loginModel.Email && u.Password == loginModel.Password);
Console.WriteLine($"User found: {user != null}");
if (user != null)
{
Console.WriteLine("Entering if block - Login successful");
// Additional logic for successful login
}
else
{
Console.WriteLine("Entering else block - Login failed");
// Logic for failed login
}
}
public class LoginModel
{
public string Email { get; set; }
public string Password { get; set; }
}
}
Hi, I’ve been trying to get this to work for the past couple of days.
I just want to create a basic login page with the user’s credentials in my local SQL server. Whenever I bruteforce the user’s information into .FirstOrDefaultAsync , it works (i replace loginModel.email and loginModel.password with a string containing that information).
However, whenever I try to make it work via the login form, it always indicates:
User found: False
Entering else block – Login failed
I can’t seem to understand why, your help would be greatly appreciated. Thanks
2
Answers
Your model property is
private
and not accessible to your .razor component.This should work:
If you change
loginModel.Email
to@loginModel.Email
then the following markup will not compile, becauseloginModel
is not accessible. Your original markup compiledloginModel.Email
as a string, but this was incorrect for data binding to theEmail
property.I resolved this issue by following this tutorial https://www.youtube.com/watch?v=Ib_NGhfvueA