Search code examples
blazormauifunction-call

How do you call a methode/function from razorcomponent-part (Maui / Blazor)?


I have a MauiBlazor app and want to navigate back to the indexpage if true:

    @page "/start"
    @inject NavigationManager NavMan

    @if (true)
    {
        @(() => NavMan.NavigateTo("/"))
    }

Output on screen is a text:"System.Action" I did expect it to navigate back to index-page!

Why and how do I do this right?


Solution

  • Your writing Razor markup not C# code.

    The Razor compiler evaluates:

    () => NavMan.NavigateTo("/")
    

    literally as a System.Action.

    To execute code you can define a RenderFragment. At which point you can roll in your conditional code as well.

    @inject NavigationManager NavMan
    
    @(this.CheckIfWeNeedToGoToHome)
    
    @code {
        private RenderFragment CheckIfWeNeedToGoToHome => (builder) =>
        {
            if (true)
                NavMan.NavigateTo("/");
        };
    }