Search code examples
c#blazorblazor-client-sideblazor-webassembly

Reading data from Blazor component


I am new to Blazor, so this will seem like an elementary problem to solve. I have a simple Blazor component that is just a text box and a button that looks like this:

<input type="text" name="" class="form-control input-user" 
    tabindex="1" @ref="UsernameControl" @bind-value="UserName" placeholder="Username...">
<button type="button" name="button" class="btn login-btn" 
    tabindex="3" @onclick="OnLoginButtonClick">Login</button>

@code {
    [Parameter] public EventCallback OnLoginButtonClick { get; set; }
    private ElementReference UsernameControl { get; set; }
    public string UserName { get; set; }
}

I have a parent control that uses this control, like this:

<UserBox OnLoginButtonClick="@LoginButtonClicked" />

@code {
    private void LoginButtonClicked()
    {
        Console.WriteLine("Clicked! ");
        Console.WriteLine(UserName); // This line doesn't work, obviously
    }
}

What I want to do is get the text that was entered in the text box. Obviously the line I posted above is not going to work. How do I get the value from the text box from my parent control? I am using @bind-value which should populate it in the UserName property, so I am sure the data is stored there, but I am not sure how to get it from the parent.


Solution

  • You could pass it as an argument to the login button clicked method for example:

    <button type="button" name="button" class="btn login-btn" tabindex="3" 
      @onclick="(() => OnLoginButtonClick(UserName))">Login</button>
    
    
    private void LoginButtonClicked(string userName)