Binding values in Blazor

42 views Asked by At

I know this is a fairly simple and noobish question, but here it goes. I have been trying to create a log-in screen with blazor.However, when I click login button, I cannot save the values.(null when I debug)

Login Page Code:

@page "/"
@attribute [StreamRendering]
@using System.ComponentModel.DataAnnotations
@using project1.Components.Models
@using project1.Services
@inject IAtLoginPage AtLoginPage
@inject ILogedIn LogedIn
@inject NavMenuViewService ViewOption

<h1>LOGIN</h1>

<EditForm Model="@loginModel" OnValidSubmit=@ValidFormSubmitted OnInvalidSubmit=@InvalidFormSubmitted FormName="LoginForm">
    <DataAnnotationsValidator />

    <div class="form-group">
        <label for="username">Username:</label>
        <InputText @bind-Value="loginModel.Username" class="form-control id="Username" />
        <ValidationMessage For="@(() => loginModel.Username)" />
    </div>

    <div class="form-group">
        <label for="password">Password:</label>
        <InputText id="password" @bind-Value="loginModel.Password" type="password" class="form-control" />
        <ValidationMessage For="@(() => loginModel.Password)" />
    </div>
    <input type="submit" class="btn btn-primary" value="Login" />
</EditForm>

@code {
    protected LoginModel loginModel;
    string LastSubmitResult;


    public void LoginCheck()
    {
        string dummyUser = "admin";
        string dummyPass = "1234";
        Console.WriteLine("Login Check");
        if ((loginModel.Username != null && loginModel.Password != null) && (dummyUser == loginModel.Username && dummyPass == loginModel.Password))
        {
            LogedIn.logInChecker = true;
        }
    }


    void ValidFormSubmitted(EditContext editContext)
    {
        LastSubmitResult = "OnValidSubmit was executed";
        LoginCheck();
    }

    void InvalidFormSubmitted(EditContext editContext)
    {
        LastSubmitResult = "OnInvalidSubmit was executed";
    }

    protected override void OnInitialized()
    {

        loginModel  = new LoginModel();
    }
}

My Model

namespace project1.Components.Models
{
    public class LoginModel
    {
        
        public string? Username { get; set; }
        public string? Password { get; set; }

        public bool RememberMe { get; set; }

    }
}

Thanks in advance!

I click login button, I cannot save the values.(null when I debug)

1

There are 1 answers

0
Alamakanambra On BEST ANSWER

This really depend on interactivity mode you have. Question is tagged blazor-wasm, but you have the [StreamRendering] attribute, which implies the the server side rendering (SSR).

In case of SSR, you have to use SupplyParameterFromForm and initialize the model only when null. As is described here. Also your model has to be a property.

 [SupplyParameterFromForm]
 public LoginModel loginModel {get;set};

 protected override void OnInitialized()
    {

        loginModel??=new();
    }