Soren
Soren

Reputation: 39

Blazor NavigationManager NullReference error in code behind

Using Blazor in VS19 Professional I'm getting a NullReference exception when I try to use the NavigationManager.NavigateTo function from the code behind .razor.cs file.

I first inject the NaviagtionManager at the top of the .razor.cs file:

[Inject]
protected NavigationManager NavigationManager { get; set; }

Then when the users clicks a submit button, data is saved to an SQL database (this part works fine) and then the page should then redirect to another page, but it fails due to "NavigationManager.get returned null" error.

This is the function saving the data and calling the NavigationManager:

public void Update() {

        participants p = new participants {
            ID = Convert.ToInt32(id),
            FirstName = participant[0].FirstName,
            LastName = participant[0].LastName,
            Eating = participant[0].Eating,
            Bowling = participant[0].Bowling,
            EscapeRoom = participant[0].EscapeRoom
        };

        this.Db.UpdateParticipant(p);
        NavigationManager.NavigateTo("Bowling/2020");
    }

I have been unable to find anything online to help me with this issue.

Does anyone have any idea how to solve this??

UPDATE WITH MORE CODE:

On the .razor page I have an EditForm which on submit calls an Update():

<EditForm Model="@participant" OnValidSubmit="@Update">

On the .razor.cs page, this is the Update() function:

public void Update() {

        participants p = new participants {
            ID = Convert.ToInt32(id),
            FirstName = participant[0].FirstName,
            LastName = participant[0].LastName,
            Eating = participant[0].Eating,
            Bowling = participant[0].Bowling,
            EscapeRoom = participant[0].EscapeRoom
        };

        this.Db.UpdateParticipant(p);
        NavigationManager.NavigateTo("/Bowling/2020/");
    }

The values in the database get updated correctly.

UPDATE:

Found the issue, see response below.

Upvotes: 1

Views: 2127

Answers (1)

Soren
Soren

Reputation: 39

This was a clear case of "don't leave anything out of your code example".

In my code I had this:

[Inject]
protected BowlingData Db { get; set; }
protected NavigationManager NavigationManager { get; set; }

(Being new to Blazor, I figured that the [Inject] would include everything following it until my [Parameters] just under this code snip.

When I posted the question, I removed the

protected BowlingData Db {get; set;} 

line to minimize the amount of example code. If I hadn't done that, I'm sure my question would have been answered right away.

As soon as I added the second [inject] my code worked as it should:

[Inject]
protected BowlingData Db { get; set; }
[Inject]
protected NavigationManager NavigationManager { get; set; }

Lessoned learned - both about Blazor and about posting questions :)

Upvotes: 2

Related Questions