this code when submit button entered invoked. in "finally" i want to set focus to an InputText but it doesn't work.
private async Task SubmitBtn()
{
if (_busy_submit_btn) return;
_busy_submit_btn = true;
try
{
var res = await myService.UpsertAsync(LetterId, myModel);
if (res.Item1 != null)
{
myModel = res.Item1;
await JsRuntime.ToastrSuccess(res.Item2);
personsInMyModel = await myService.GetPersonWithLetterIdAsync(LetterId);
}
else
{
await JsRuntime.ToastrError(res.Item2);
}
myModel = new myDTO();
}
finally
{
_busy_submit_btn = false;
await JsRuntime.InvokeVoidAsync("focusElementById", "NCode");
}
}
Set focus on an element after submit
The page below demonstrates settting the focus on first load and after a submit.
@page "/"
<PageTitle>Index</PageTitle>
<h1>Hello, world!</h1>
<EditForm Model=this.country OnSubmit=this.Submit>
<input class="form-control mb-3" @bind=this.country.Name @ref=this.firstElement />
<input class="form-control mb-3" @bind=this.country.Continent @ref=this.focusElement />
<button class="btn btn-primary" type="submit">Submit</button>
</EditForm>
@code {
private ElementReference firstElement;
private ElementReference focusElement;
private Country country = new() { Name="Spain", Continent="Europe" };
private async Task Submit()
{
//Do domething async
await Task.Delay(100);
await focusElement.FocusAsync();
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
// Set focus to the first input element in the modal
await firstElement.FocusAsync();
}
}
public class Country
{
public string? Name { get; set; }
public string? Continent { get; set; }
}
}
I am using an EditForm - when I change model instance, it drops and recreates the elements in the DOM - so it will need to set focus in OnAfterRenderAsync instead.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.