Reputation: 48686
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.
Upvotes: 0
Views: 807
Reputation: 16
try this:
parent component
<UserBox OnLoginButtonClick="@LoginButtonClicked" />
@code {
private void LoginButtonClicked(string UserName)
{
Console.WriteLine("Clicked! ");
Console.WriteLine(UserName); // This line doesn't work, obviously
}
}
and you parent
<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="Login">Login</button>
@code {
[Parameter] public EventCallback<string> OnLoginButtonClick { get; set; }
private ElementReference UsernameControl { get; set; }
public string UserName { get; set; }
public async Task Login()
{
await OnLoginButtonClick.InvokeAsync(UserName);
}
}
Upvotes: 0
Reputation: 23224
Change your EventCallback
to an EventCallback<string>
, then you can invoke it with a string value.
Upvotes: 0
Reputation: 1333
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)
Upvotes: 1