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
--%>
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?
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.