Search code examples
c#razorblazorblazor-server-siderazor-components

Executing async method on button click Blazor Server


I am trying to execute an asynchronous method when pressing a button. The code compiles without issue, but when the button is clicked the method is never called. I have used all the google fu i have at my disposal to no avail. Am I doing something wrong syntactically? Did i forget to import something or am i misunderstanding how this works?

  @foreach (Data.Course cor in CourseList)
                    { 
/...
<button class="btn btn-outline-primary" @onclick="@(async () => await EnrollCourse(cor.CourseId))">
                                        Enroll
                                    </button>
}

@functions{
    private async Task EnrollCourse(int corid)
    {
        var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
        string userid = authState.User.Identity.Name;
        await _db.EnrollCourse(corid, userid);
        NavigationManager.NavigateTo($"/course/{corid}");
        
    }



}


Solution

  • For anyone that comes around to this on google, i ended up setting the button to redirect to a different page that runs the code and redirects to the final page.

    <div class="button">
        <a href="/enroll/@cor.CourseId">Enroll</a>
    </div>
    
    @page "/enroll/{course}"
    @inject Data.CourseData _db
    @inject NavigationManager NavigationManager
    @inject AuthenticationStateProvider AuthenticationStateProvider
    @inject Microsoft.AspNetCore.Identity.UserManager<Microsoft.AspNetCore.Identity.IdentityUser> userManager
    @using System.Security.Claims
    
    
    @code {
        [Parameter]
        public string course { get; set; }
        protected override async Task OnInitializedAsync()
        {
            var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
    
            var user = await userManager.GetUserAsync(authState.User);
            if (user != null)
            {
                string userid = user.Id;
                await _db.EnrollCourse(Int32.Parse(course), userid);
                NavigationManager.NavigateTo("/course/" + Int32.Parse(course));
    
    
            }
        }
    
    }