Home > Mobile >  How to pass data from Layout to Razor Page
How to pass data from Layout to Razor Page

Time:06-07

I am using the below code at the beginning of my _Layout.cshtml.

@{
    bool isAuthenticated = false;
    var userPingDTO = new UserPingDTO();
    try
    {
        userPingDTO = await userData.GetUserPing();
        isAuthenticated = true;

    }
    catch (Exception e)
    {
        Console.WriteLine(e);
        isAuthenticated = false;
    }
}

It is used to check if a user is logged in. What i want to do is make available the isAuthenticated variable to all Razor Pages. So for example an Index.cshtml page can access the isAuthenticated variable.

Edit for clarification: I have tried to use ViewBag etc but they don't seem to work. The code i sent above exists inside the _Layout file, not in the page file. So what i want is Layout->Page. If i put breakpoints the @page code seems to be hit first. After that the Layout code is hit. So ViewBag works for Page->Layout but not for Layout->Page.

CodePudding user response:

I was approaching the problem the wrong way. Code that has to be executed on the start of every page load has to be placed in a _ViewStart file instead of the _Layout file. So the order of execution is _Viewstart->Page->_Layout. After populating the ViewData with the specific value in the _ViewStart file everything worked correctly. From the documentation: https://docs.microsoft.com/en-us/aspnet/core/mvc/views/layout?view=aspnetcore-6.0

Code that needs to run before each view or page should be placed in the _ViewStart.cshtml file.

  • Related