Define global variable in _ViewStart.cshtml

Viewed 2736

We are using .NET Core 3.1. We want to define a global variable (current user's email) in _ViewStart.cshtml so that all other views can access it. By doing this, we aim to avoid the repetitive code.

The following code:

@using System.Security.Claims
Your email: @User.FindFirstValue(MyClaimTypes.Email)

could be replaced with just this:

Your email: @email

I tried defining email in _ViewStart.cshtml like so:

@{
    Layout = "_MyLayout";
    string email = "test@test.com";
}

and later accessing it in Index.cshtml:

Your email: @email

But it says that

The name 'email' does not exist in the current context.

How can we access variable defined in _ViewStart.cshtml from all other views?

1 Answers

In the _ViewImports.cshtml you can inject the variable like this:

@using MyApp.AspNetCore
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

@{ 
    string UserEmail = "test@test.com";
}
@inject string UserEmail;

In the Index.cshtml you can reference it by its name:

<span>Hello @UserEmail </span>
Related