如果我在 ASP.NET MVC 视图中有如下代码:
<%
bool admin = false;
if (ViewData.ContainsKey("isAdmin"))
{
admin = (bool)ViewData["isAdmin"];
}
if (admin)
{
%>
<%--
... generate table of html
--%>
然后在页面下方,我在另一个代码渲染块中创建另一个脚本<% %>
,我可以重复使用吗admin
变量,它会记住页面上层的状态,还是范围就在<% %>
blocks?
以下是我注意到的有关 MVC 范围的内容:
内容控件中声明的变量的作用域仅在内容控件内:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
ScopeTest
<%
string testVar1 = "This is a test.";
%>
<%=
testVar1
%>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>ScopeTest</h2>
The below reference to the testVar1 will cause a parser error, because the variable is out of scope.
<%=testVar1 %>
</asp:Content>
**在没有 MasterPage 的视图页面中,在 runat="server" 控件中声明的变量仅在该控件中可用。在 runat="server" 控件外部声明的变量对该控件不可用。
否则,声明的变量在整个页面中都可用。**
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<%
string strPageScope = "PageScope Variable.";
%>
<head runat="server">
[HEAD]<br />
<title>ScopeTest2</title>
<%
string strHeadScope = "Head Scope...";
%>
This WORKS:
<%=
strHeadScope %>
<br />
ViewData available everywhere:
<%=
ViewData["VDScope"].ToString()
%>
<br />
strPageScope is NOT Available BECAUSE THE RUNAT=SERVER:
<%
//Response.Write(strPageScope);
%>
<br />
[END OF HEAD]<br />
</head>
<body>
[BODY START]<br />
strHeadScope NOT AVAILABLE, BECAUSE THE HEAD HAS RUNAT="SERVER" IN IT.
<%
//Response.Write(strHeadScope);
%>
<br />
ViewData is available everywhere:
<%
Response.Write( ViewData["VDScope"].ToString());
%>
<br />
<div>
<%
string strBodyVar = "Testing Var Declared in Body.";
%>
</div>
<%
Response.Write(strBodyVar);
%>
<br />
Page Scope works:
<%=
strPageScope
%>
<br />
[END BODY]
</body>
</html>
控制器代码,如果好奇的话:
公共 ActionResult 范围测试()
{
返回视图();
}
public ActionResult ScopeTest2()
{
ViewData["VDScope"] = "ViewDataScope";
return View();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)