C#Razor该名称在当前上下文中不存在

C#Razor该名称在当前上下文中不存在,c#,asp.net-mvc,razor,C#,Asp.net Mvc,Razor,我知道我在这里一定很愚蠢,但我不明白为什么这个代码不起作用。我对剃须刀很陌生,所以请对我宽容一点 我在我的标记中有以下代码:(我已经将它简化为尽可能简单的代码,同时仍然复制问题,以便我能够更容易地诊断问题) 它返回以下内容: error CS0103: The name 'testVar' does not exist in the current context 我尝试过为变量使用不同的名称,我尝试过让它在声明中使用“var”而不是“string”,我尝试过为它分配不同的值,我尝试过用括号括

我知道我在这里一定很愚蠢,但我不明白为什么这个代码不起作用。我对剃须刀很陌生,所以请对我宽容一点

我在我的标记中有以下代码:(我已经将它简化为尽可能简单的代码,同时仍然复制问题,以便我能够更容易地诊断问题)

它返回以下内容:

error CS0103: The name 'testVar' does not exist in the current context
我尝试过为变量使用不同的名称,我尝试过让它在声明中使用“var”而不是“string”,我尝试过为它分配不同的值,我尝试过用括号括住变量,比如
@(testVar)
,但问题仍然存在。这非常令人沮丧,因为在我的代码的另一部分中

string prop = @p.Name + " (" + @p.PropertyType + ") - " + @p.GetValue(@page, null).ToString() + "\r\n";
@prop
这很好用

我想不出是什么原因导致了它,它开始让我感到沮丧

谢谢


YM

在Razor中,当我们想要编写c#语句时,我们必须告诉它c#代码从这里开始:

@{   // from here c# block starts
string testVar = "test";

}  // here ends
现在,如果要在html中访问此变量,可以执行以下操作:

<span>@testVar</span>
它被视为纯文本,将在浏览器上呈现,如“string prop=…” 您必须通过以下方式确定它是c代码:

@{
string prop = @p.Name + " (" + @p.PropertyType + ") - " + @p.GetValue(@page, null).ToString() + "\r\n";
}

当我问这个问题时,我知道我在做一些愚蠢的事情,但我不得不问它来找出答案。谢谢你,这正是我没有做的。
string prop = @p.Name + " (" + @p.PropertyType + ") - " + @p.GetValue(@page, null).ToString() + "\r\n";
@{
string prop = @p.Name + " (" + @p.PropertyType + ") - " + @p.GetValue(@page, null).ToString() + "\r\n";
}