novfal haq
novfal haq

Reputation: 117

How Redirect the page the in blazor Class file

If using Navigatiomanager null value exception came while using in Class file

NavigationManager navigationManager;
  public ICollection<TimeOff> GetTimeOffbyStaff(int id)
    {
      ICollection<TimeOff> timeOff = new List<TimeOff>();
      try
      {
        timeOff = labOrgDbContext.TimeOff.Include(x => x.Technologist).Where(x => x.TechnologistId == id && x.FromDate >= (DateTime.Now.AddYears(-1)).Date && x.IsDeleted != true).OrderByDescending(x => x.RowInsertOn).ToList();
      }
      catch (Exception ex)
      {
        ExceptionLogging.SendErrorToText(ex, "1");
        navigationManager.NavigateTo("/PagenotFound");
        throw ex;
      }
      return timeOff;
    }

Upvotes: 1

Views: 2492

Answers (1)

rk72
rk72

Reputation: 1098

Refactor your code to not mix logic together with page navigation. Ie. have one class that will provide the "time off by staff" calculation. Then use that class in a visual page that will inject NavigationManager, and do the page navigation in case of error like this:

@page "/"
@inject NavigationManager navigationManager; // inject an instance of NavigationManager

<h1>Time-off by staff</h1>

Some page content.....

<button @onclick="GetTimeOffByStaff">Get time off by staff</button>

@code {
    void GetTimeOffByStaff()
    {
        try
        {
            TimeOffLogic logic = new TimeOffLogic();    // this will be your logic class

            var timeOff = logic.GetTimeOffbyStaff(id);
        }
        catch (Exception ex)
        {
            ExceptionLogging.SendErrorToText(ex, "1");
            navigationManager.NavigateTo("/PagenotFound");      // use NavigationManager
        }

        // do something with timeOff
    }
}

Upvotes: 1

Related Questions