Calling async methods in Blazor view

后端 未结 2 1871
刺人心
刺人心 2020-12-10 16:49

I have a server-side blazor client and I\'m trying to modify the MainLayout razor page by having a Login check. I\'m currently using Blazored for localstorage saving, and I\

相关标签:
2条回答
  • 2020-12-10 17:07

    is there a way to execute async methods in razor pages?

    No, there isn't a way to use await in a Razor component. This is because you can't do async work as part of the rendering of the component.

    Incidentally, the local storage mechanism provided by the Blazor team supports data protection, and is recommended for use by Steve Sanderson.

    Note: The async Lifecycle methods of the component are where async work is done, and thus you can design your code accordingly, as for instance, calling AppState.IsLoggedIn() from OnInitializedAsync, and assigning the returned value to a local variable which can be accessed from your views.

    0 讨论(0)
  • 2020-12-10 17:13

    AsyncComponent.razor

        @typeparam TResult
        @typeparam TInput
        @if (Result != null)
        {
            @DataReadyFragment(Result)
        }
        else if (DataMissingFragment != null)
        {
            @DataMissingFragment
        }
        @code {
            [Parameter] public RenderFragment<TResult> DataReadyFragment { get; set; }
            [Parameter] public RenderFragment DataMissingFragment { get; set; }
            [Parameter] public Func<TInput, Task<TResult>> AsyncOperation { get; set; }
            [Parameter] public TInput Input { get; set; }
            TResult Result { get; set; }
    
            protected override async Task OnAfterRenderAsync(bool firstRender)
            {
                if(firstRender)
    AsyncOperation.Invoke(Input).ContinueWith(t => { Result = t.Result; InvokeAsync(StateHasChanged); });
            }
        }
    

    Usage

    <AsyncComponent TResult="User" TInput="string" Input="Pa$$W0rd" AsyncOperation="@AsyncMethodName">
        <DataReadyFragment Context="result">
            @if(result.IsLoggedIn)
             {
               <h3>Logged-In , Username:@result.Name</h3>
             }
             else
             {
              <h3>Wrong Password</h3>
             }
        </DataReadyFragment>
        <DataMissingFragment>
            <h3>Please Login :)</h3>
        </DataMissingFragment>
    </AsyncComponent>
    
    0 讨论(0)
提交回复
热议问题