Reputation: 621
I am using blazor to do a search. When I press a key in the input it checks if its an enter key and if it is then initiates the search. However, it appears that the value of the binded variable(keywordValue) does not update until i hit enter twice in a row. The first time if i press it the value is not updated.
<h1>Blogs</h1>
<fieldset>
<label>Keyword Search</label>
<input type="text" @bind="keywordValue" @bind:event="oninput" @onkeypress="KeywordEnterPressed"/>
<button type="submit" @onclick="SearchBlogs">Search</button>
</fieldset>
private string keywordValue { get; set; }
protected async void KeywordEnterPressed(KeyboardEventArgs eventArgs)
{
if (eventArgs.Key == "Enter")
{
await SearchBlogs();
}
}
For example: If i type "test" into the input field and press enter it runs searchblogs() with a value of "". When i hit enter again then it runs searchblogs() with a value of "test" like it should.
Upvotes: 4
Views: 8915
Reputation: 183
Because of the event ordering, I got this to work by using "onkeyup" instead of "onkeypress"
Upvotes: 10
Reputation: 231
As per Nick's comment it appears to be the event ordering, binding not happened when key pressed event is run. I added a Task.Delay(100) to the key pressed event before the search to allow time for the binding and now behaving for me. Not great as the 100 is totally arbitary.
Upvotes: 2
Reputation: 45586
You should use Task instead of void
Write: protected async Task KeywordEnterPressed
instead of protected async void KeywordEnterPressed
Incidentaly, the type of the button element should be "button" instead of"submit"
Do this : <button type="button" @onclick="SearchBlogs">
instead of <button type="submit" @onclick="SearchBlogs">
Hope this helps...
Upvotes: 2