开发者

<% %> in ASP.NET (embedded code blocks)

I understand what these signify in the markup of the aspx pages ... but I don't not know the full power they can be used for or even the name to denote these开发者_JAVA百科 special directives.

Example:

can i put conditional statements like ifs or switches

I have seen and used them to bind data from a data set for example

Any input is greatly appreciated


Here (or here - in case it moves again) is a post I found and stashed away some time ago listing all the different inline server-side tags with examples. There are seven:

  1. <%...%> runs normal code
  2. <%=...%> is equivalent to Response.Write()
  3. <%#...%> is used for databinding expressions
  4. <%$...%> returns the value of an expression, and can be used in parameters (note: expressions are not code - see here)
  5. <%@...%> is for page directives, usually at the top of the ASPX file
  6. <%--...--%> is for comments
  7. <%:...%> is the same as <%= except it HTML-encodes the value


These are code Block tags.

And yes you can wrap serverside code in these tags (examples in C#)

<% if (x = y) {
  } else {
  }
%>

OR

<% if (x = y) {%>
   Write this HTML
<%  } else {%>
   Write this html
<%  }%>

There is also

This <%=SomeVar %> Which will out put SomeVar to HTML


The MSDN documentation calls them embedded code blocks. You can put pretty much any code you would place in code-behind files and the server will execute them before serving your pages to browsers.

Directive is the name given to one particular type of code block, the one most commonly seen at the top of ASP.NET pages to give the compiler information about your ASP.NET pages. They are delimited by <%@ and %>.

The language of the code blocks is the same one as specified in the directive block. A quick example:

<%@ Page Language="C#" %>
<!DOCTYPE html>
<html>
  <body>
    <p><% string hello = "Hello world!"; Response.Write(hello); %></p>
    <ol>
    <% for (int i = 1; i <= 5; ++i) { %>
        <li><% Response.Write("Item #" + i); %></li>
    <% } %>
    </ol>
  </body>
</html>


When the server receives a request for an ASPX page, it generates an in-memory class that inherits from Page (or whatever base class you specified). The inherited class translates "normal" markup into static Response.Write() calls, <%...%> into equivalent code, and <%= someExpression %> into Response.Write(someExpression). For the former code block, any valid C# (or VB) should be accepted; for the latter, the embedded code must be a single expression (something you could assign to a variable.


Yes, those symbols indicate to the server parsing the page that the code within those tags should be interpreted as code and not HTML.

So, to answer your other question, you can use conditionals and most any other programming features supported by the server.

Check out a quick guide to ASP: http://www.w3schools.com/asp/default.asp

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜