Home > OS >  Blazor NavigationManager works but Redirects backs To same Page Immediately
Blazor NavigationManager works but Redirects backs To same Page Immediately

Time:09-17

This is my Index.razor Page.


@page "/"
@inject NavigationManager navigation
<PageTitle>Index</PageTitle>

    <div >
      <div >
        <div >
          <div >
            <h3>LOGIN</h3>
            <p>Please enter your credentials to login.</p>
          </div>
        </div>
        <form >
          <input type="text" placeholder="username"/>
          <input type="password" placeholder="password"/>
          <button @onclick=ValidateCredentials>login</button>
        </form>
      </div>
    </div>

@code{
    protected override async Task OnInitializedAsync()
    {
        
    }
    public void ValidateCredentials(EventArgs e)
    {
        navigation.NavigateTo("/fetchdata");
    }
}

When I click on Login button over the UI the fetchdata pages pops but immediately the index.razor pages comes back eg Onclick from Index.razor ->fetchdata.razor(it appears for millisecond)-->index.razor login uI starts showing.

Please guide me what am I doing wrong.I am very new to Blazor but i guess this (It could onclick event call from html form I might to use Editcontext model )

CodePudding user response:

It's likely due to a client side redirect. Try passing true as the second parameter to the NavigateTo(string uri, bool forceLoad) overload.

navgation.NavigateTo("/fetchdata", forceLoad: true);

CodePudding user response:

Explanation: Since you embed a button Html element within a form element, the type attribute of the button element defaults to "submit", which is why the first action performed is the submission of the form to nowhere, as your app is an SPA... No traditional post request are employed in SPA Apps.

navgation.NavigateTo("/fetchdata", forceLoad: true); is wrong. The component FetchData is within the boundary space of your App, and it should be called with forceLoad: false. When you want to go out of the boundary space of your App, say you want to navigate to the url "example.com", you should use forceLoad: true.

When you use navgation.NavigateTo("/fetchdata", forceLoad: true);, you actually reload your App anew. And this was and should not be your intention.

How to solve this issue ? Place the button element outside the form element, and it would be a good practice to set the type attribute to button, like this:

<form >
          <input type="text" placeholder="username"/>
          <input type="password" placeholder="password"/>
 </form>

 <button type="button" @onclick=ValidateCredentials>login</button>

And

public void ValidateCredentials(EventArgs e)
{
     navigation.NavigateTo("/fetchdata");
}

Did you notice that the form element is superfluous ?

It's now good time to learn Blazor. Begin at the beginning

  • Related