Reputation: 187
I created a new, clean Blazor WASM project, and added following minimal sample to bottom of index page:
<EditForm Model="FormModel" OnSubmit="OnSubmit">
<InputText @bind-Value="FormModel" />
<button type="submit">Submit</button>
</EditForm>
@code {
public string FormModel { get; set; } = "";
public async Task OnSubmit(EditContext context) => Console.WriteLine("Clicked");
}
When I focus textbox, write something and then click on submit button nothing happens. Only on second click the message appears in console.
This looks like a blazor bug but with many tickets regarding this issue it always turned out to be in fact error in user code. However, none of the solutions or reasons I found apply to this minimal case.
Is there anything I am missing? I would - obviously - like the button to not ignore the first click.
Upvotes: 3
Views: 1952
Reputation: 45596
this issue it always turned out to be in fact error in user code
That's right...
What you're doing here is binding your EditForm (Model attribute) to a string property on the one hand, and binding the InputText component to the very same property. The Model parameter should be of object type, whereas the Value property of the InputText component is string, which initially contains the value null, which you probably have noticed as the compiler expects the EditForm's Model parameter or the EditForm's EditContext parameter be provided, and not null. So you innocently assigned an empty string value to the FormModel property, thus appeasing the compiler, but your code is still malformed, and there is a price to pay for this...
Whenever you click on the "submit" button, the OnSubmit event handler is called, and you are expected to handle the submission yourself which you do not do. Since the "submit" button is embedded within a form, once you click on the button the submit action is performed, and the form is posted, to the outer space... the execution flow is no longer in the Blazor SPA. After the submission of the form data to outer space and returning back, the second submission call Console.WriteLine("Clicked");
Note that if you use the OnValidSumit event, Blazor JSInterop intercept the submission action and cancel it. The concept of Form submission does not exist in Blazor. All the Blazor application takes place with a single miserable page; this is the SPA space. Again,if you use the OnSubmit event handler, you must intercept the submission action and cancel it yourself, before going to outer space.
Upvotes: 2
Reputation: 187
I found a workaround for the issue, wrapping model with another object seems to fix the problem:
<EditForm Model="Model" OnSubmit="OnSubmit">
<InputText @bind-Value="Model.Value" />
<button type="submit">
<div>Submit</div>
</button>
</EditForm>
@code {
public class FormModel {
public string Value { get; set; }
}
public FormModel Model { get; set; } = new FormModel();
public async Task OnSubmit(EditContext context) => Console.WriteLine("Clicked");
}
Upvotes: 2