How to keep a global variable's value when refreshing the page content in Asp.Net Blazor

474 Views Asked by At

This application is ASP.Net Blazor version 7. The application is a quote system. While the user is working on a quote, the quote number is stored in a global variable using a state container. There is a product details page on which the user can click a button to add the item to the quote as long as there is an active quote number stored in the global variable. There are substitute items on the product details page which the user can click on to view that product. The substitute item details route to the same component as the product details. The problem is that in order to get the substitute item details to display on the page, I need to use the NavigationManager NavigateTo and force the page to load otherwise the item details on the page do not get updated. However, forcing the page to load removes the quote number from the global variable. Once the quote number is lost, the user can no longer add items to the quote. I tried using an href and NavLink but neither one would update the contents of the page.

How can I refresh the content of the page without losing the value in the global variable?

public class QuoteIdentifier
{
    public string QuoteNumber { get; private set; }
    public event Action OnChange;

    public void SetQuoteNumber(string id)
    {
        QuoteNumber = id;
        NotifyStateChanged();
    }

    public void Reset()
    {
        QuoteNumber = null;
        NotifyStateChanged();
    }

    void NotifyStateChanged() => OnChange?.Invoke();
}

product details page

@page "/Products/Product/{PartNo}"
[Inject]
public QuoteIdentifier QuoteIdentifier { get; set; }

void NavigateTo(string itemNo)
{
    NavManager.NavigateTo($"/Products/Product/{NavManager.UrlEncode(itemNo)}", true);
}

edit

I was populating all of my page content in the OnInitialized method which only fires once, thus forcing me to reload the page to get the new page contents to show. I moved the code to populate the content to the OnParametersSet method, removed the forced reload in the NavigateTo, reset my object which holds my page content when my parameter is set, and the content now displays and I do not lose the value of my quote number.

0

There are 0 best solutions below