Terrence
Terrence

Reputation: 341

Blazor Navigation Issue

I have 2 Blazor pages.

Home.razor @page "/"

MgrLanding.razor @page "/MgrLanding"

And one component PersonEdit.razor

The home page has a link on it to navigate to MrgLanding page. When I click that link it takes me to MgrLanding.

MgrLanding has the PersonEdit component.

There is a link to show the PersonEdit component.

When I clik on the link it takes me back to the Home page.

If I make the MgrLanding page the home page by: @page "/" The behavior is as expected, the PersonEdit component shows.

HomePage.razor

@page "/"
<h3>HomePage</h3>
<a href="/MgrLanding">Mgr Landing Page</a>

MgrLanding.razor

@page "/MgrLanding"

<h3>MgrLanding</h3>

<a href="" onclick="@ChangeEditMode">Edit</a>

@if (EditMode)
{
    <PersonEdit Employee=@PE FormSubmittedCallback=@Save></PersonEdit>
}

@code {
    public bool EditMode { get; set; }
    public Person PE { get; set; }

    public class Person
    {
        public string Name { get; set; }
    }

    protected async override Task OnInitializedAsync()
    {
        PE = new Person();
        PE.Name = "Bob The Builder";
    }
    protected void ChangeEditMode()
    {
        EditMode = true;
    }
    public void Save()
    {
        EditMode = false;
    }
}

PersonEdit.razor component

<h5>PersonEdit Component</h5>

<EditForm Context="formContext" Model=@Employee>
    <InputText @bind-Value=Employee.Name class="form-control" id="Name" />
    <input type="submit" class="btn btn-primary" value="Save" @onclick="Save" />
</EditForm>

@code {
    [Parameter]
    public MgrLanding.Person Employee { get; set; }
    [Parameter]
    public EventCallback FormSubmittedCallback { get; set; }

    private void Save()
    {
        FormSubmittedCallback.InvokeAsync();
    }
}

Upvotes: 0

Views: 409

Answers (2)

Brian Parker
Brian Parker

Reputation: 14523

Change your anchor to a button:

<a href="" onclick="@ChangeEditMode">Edit</a>

to

<button onclick="@ChangeEditMode">Edit</button>

if using an anchor for and action is required then a better blazor way would be simply omit the href attribute:

<a onclick="@ChangeEditMode">Edit</a>

if styling of a link is required i would

<button class="btn btn-link" onclick="@ChangeEditMode">Edit</button>

Upvotes: 2

Surinder Singh
Surinder Singh

Reputation: 1450

You can still use link and prevent its default action

<a href="" @onclick:preventDefault=true 
 @onclick="@ChangeEditMode">Edit</a>

Upvotes: 0

Related Questions