Ale*_*jic 3 c# asp.net-core-mvc asp.net-core-3.1
我们正在使用.NET Core 3.1. 我们想要定义一个全局变量(当前用户的电子邮件),_ViewStart.cshtml以便所有其他视图都可以访问它。通过这样做,我们的目的是避免重复的代码。
下面的代码:
@using System.Security.Claims
Your email: @User.FindFirstValue(MyClaimTypes.Email)
Run Code Online (Sandbox Code Playgroud)
可以用这个来代替:
Your email: @email
Run Code Online (Sandbox Code Playgroud)
我尝试_ViewStart.cshtml像这样定义电子邮件:
@{
Layout = "_MyLayout";
string email = "test@test.com";
}
Run Code Online (Sandbox Code Playgroud)
然后在以下位置访问它Index.cshtml:
Your email: @email
Run Code Online (Sandbox Code Playgroud)
但它说
当前上下文中不存在名称“email”。
我们如何_ViewStart.cshtml从所有其他视图访问定义的变量?
在 中,_ViewImports.cshtml您可以像这样注入变量:
@using MyApp.AspNetCore
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@{
string UserEmail = "test@test.com";
}
@inject string UserEmail;
Run Code Online (Sandbox Code Playgroud)
在 中,Index.cshtml您可以通过其名称引用它:
<span>Hello @UserEmail </span>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5584 次 |
| 最近记录: |