Object reference not set when using keypress to trigger a button in Blazor

Viewed 209

I have a chat program, consisting of an input textbox and a send button, set up like this:

<input @bind="messageInput" size="50" @onkeydown="submitMessageInput" />

<button @onclick="Send">Send</button>

The Send method does this:

async Task Send()
        {
            if (messageInput.StartsWith("/login") .....

The submitMessageInput method looks like this in order to handle pressing enter rather than clicking the send button manually:

public async Task submitMessageInput(KeyboardEventArgs e)
        {
            if (e.Code == "Enter" || e.Code == "NumpadEnter")
            {
                await Send();
            }
        }

If the button is clicked, it works fine. However if enter is pressed, the first line of the Send() method throws an object not set to instance of an object error.

I wonder if it's some kind of context issue that's making messageInput null? What's the correct way to handle this situation?

2 Answers

So it seems that @bind="someString" is an abbreviation that sets two properties, @bind-value="someString" and @bind-value:event="onchange"

The value therefore updates whenever a change event is registered, which is when the input loses focus.

To fix the issue you need to change onchange to oninput. It will then update the variable every time you enter a character, fixing the problem.

Just change event onkeydown to onkeyup. The fact is that the 'messageInput' field will be updated after the @onkeydown event, but the field has already been updated when the @onkeyup event occurs.

<input @bind-value="messageInput" size="50" @onkeyup="submitMessageInput" />
<button @onclick="Send">Send</button>
@code {
    protected string messageInput;
    public async Task submitMessageInput(KeyboardEventArgs e) {
        if (e.Code == "Enter" || e.Code == "NumpadEnter") {
            await Send();
        }
    }

    protected async Task Send() {
        if (messageInput.StartsWith("/login")) {
            // to do
        }
    }
}
Related