一个什么是一个视图内的变量的范围有多大? [英] What is a the scope of a variables inside a view?
问题描述
如果我有code,看起来像这样一个ASP.NET MVC视图中:
If I have code inside an ASP.NET MVC view that looks like this:
<%
bool admin = false;
if (ViewData.ContainsKey("isAdmin"))
{
admin = (bool)ViewData["isAdmin"];
}
if (admin)
{
%>
<%--
... generate table of html
--%>
和后来在页面创建在另一个code另一个脚本渲染块&LT;%%&GT;
,我可以重复使用管理员
变量,将其从网页需要更高的记忆状态,或者是范围只是在&LT;%%&GT;
块
and later down the page I create another script inside another code render block <% %>
, can I reuse the admin
variable and will it remember the state from higher in the page, or is the scope just inside the <% %>
blocks?
推荐答案
变量通常在一个视图范围,但它可以得到标签混淆。认为整个视图与标签(和标签本身)为空白之外的一切的单一方法。在视图中块之外定义的变量将范围限定为整个视图。一个块中定义的变量(foreach循环/如果再把/使用)将作用域该块。你不能重复使用具有pviously被外块定义$ P $一个块中的一个变量。
Variables are scoped normally in a view, though it can get confusing with the tags. Think of the whole view as a single method with everything outside the tags (and the tags themselves) as whitespace. A variable defined outside a block in the view will be scoped to the entire view. A variable defined inside a block (foreach loop/if then/using) will be scoped to that block. You can't reuse a variable inside a block that has previously been defined outside the block.
这篇关于一个什么是一个视图内的变量的范围有多大?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!