无法访问剃刀页面中的变量
Unable to access variable in razor page
我的项目中有以下 razor 页面:
@using XditProj.Models
@model List<XditProj.Models.UserViewModel>
<link rel="stylesheet" href="../../wwwroot/css/askStyles.css">
<link rel="stylesheet" href="../../wwwroot/css/bootstrap.min.css">
<link rel="stylesheet" href="../../wwwroot/css/bootstrap.min.css">
@foreach (UserViewModel user in @Model)
{
@{
var currentLocalModel = user.moneyStats;
var one = "weekly price:";
string two = "saved from last week:";
string three = "yearly Spending:";
};
<div class="row">
<div class="col-sm-3">
<div class="well red">
<p>@user.UserName </p>
</div>
</div>
<div class="col-sm-9">
<div class="well neutral">
<p> @user.status</p>
<div class="bottom-left-text">
<span class="label label-default">@one </span>
<span class="label label-primary">Total KWH: 200</span>
<span class="label label-success">Labels</span>
</div>
</div>
</div>
</div>
}
我的问题是关于 <span class="label label-default">@one </span>
行,我试图访问我刚刚声明的变量 one
。但是我的 ide 吓坏了,找不到那个名字的任何东西。
为什么我无法访问变量?
在 C# 中,花括号 ({}
) 为变量创建了一个新的作用域。在“内部”范围内声明的变量在“外部”范围内不可访问。我认为没有必要在这里声明一个新的范围,所以你可以删除它:
@foreach (UserViewModel user in @Model)
{
var currentLocalModel = user.moneyStats;
var one = "weekly price:";
string two = "saved from last week:";
string three = "yearly Spending:";
<div class="row">
...
您 可以 还可以在 foreach
之外声明 one
、two
和 three
,因为它们的值不改变,但没有必要让脚本工作,
我的项目中有以下 razor 页面:
@using XditProj.Models
@model List<XditProj.Models.UserViewModel>
<link rel="stylesheet" href="../../wwwroot/css/askStyles.css">
<link rel="stylesheet" href="../../wwwroot/css/bootstrap.min.css">
<link rel="stylesheet" href="../../wwwroot/css/bootstrap.min.css">
@foreach (UserViewModel user in @Model)
{
@{
var currentLocalModel = user.moneyStats;
var one = "weekly price:";
string two = "saved from last week:";
string three = "yearly Spending:";
};
<div class="row">
<div class="col-sm-3">
<div class="well red">
<p>@user.UserName </p>
</div>
</div>
<div class="col-sm-9">
<div class="well neutral">
<p> @user.status</p>
<div class="bottom-left-text">
<span class="label label-default">@one </span>
<span class="label label-primary">Total KWH: 200</span>
<span class="label label-success">Labels</span>
</div>
</div>
</div>
</div>
}
我的问题是关于 <span class="label label-default">@one </span>
行,我试图访问我刚刚声明的变量 one
。但是我的 ide 吓坏了,找不到那个名字的任何东西。
为什么我无法访问变量?
在 C# 中,花括号 ({}
) 为变量创建了一个新的作用域。在“内部”范围内声明的变量在“外部”范围内不可访问。我认为没有必要在这里声明一个新的范围,所以你可以删除它:
@foreach (UserViewModel user in @Model)
{
var currentLocalModel = user.moneyStats;
var one = "weekly price:";
string two = "saved from last week:";
string three = "yearly Spending:";
<div class="row">
...
您 可以 还可以在 foreach
之外声明 one
、two
和 three
,因为它们的值不改变,但没有必要让脚本工作,