在视图的一部分中无法访问声明的变量

时间:2012-09-07 11:50:37

标签: asp.net-mvc

有一件奇怪的事情。我在视图开始时声明了一些变量,但在标签中它无法访问。我可以在标签之间声明具有相同名称的变量。在标签之外,原始变量可以再次访问。

也许,原因可能是有runatserver。 代码如下所示:

<% var variable = something; %>
<head id="Head1" runat="server">
<%!-- <% variable = something else; %> --%> // impossible variable don't exist in this context
<% var variable = something else %> // so this row instead of last one 
...
</head>
<% if (variable == something) 
       ThisFunctionWillBeExecute();
   if (variable == somethigelse)
       ThisFunctionWillNotBeExecuted();
%>

我不明白为什么,我不能谷歌一些解释。你懂这个了吗?一些链接?它是如何工作的,代码的一部分是单独处理的?

难道我不知道为什么有这个奇怪的解决方案,我不是代码的作者,我只是做了一些修改。

编辑:我忘了写这是主页。

1 个答案:

答案 0 :(得分:0)

在ASP.NET MVC上下文中,如果在任何元素(例如DIV)上使用runat="server"标记,它将在编译页面中将该代码呈现为单独的方法。因此,任何现有变量都不在上下文中,而在该标记中声明的变量在runat="server"标记之后超出了上下文。

来源: What is the status of runat="server" tags in ASP.NET MVC?

相关问题