Possible Duplicate:
ASP.NET “special” tags
I am trying to understand an MVC application. It has multiple user controls. In these controls I see syntax like:<%= ...some text ... %>
I have also seen:<%: ...some text ... %>
<@ ...some text ... %>
<% ...some text ... %>
<%# ...some text ... %>
I can see that it enables me to write code in the control/javascript but I don't fully understand the difference between %, %:, %= and %#.
When are they "executed/evaluated"?
Is there a difference if <%= ... =>
is in a user control or enclosed in single quotes in a Javascript function?
I am not even sure if my title is correct, I don't get anything when googling it. So I would be delighted with an explanation, more than happy with a link to documentation and happy with the correct terminology.
Assuming you are using the WebForms view engine in ASP.NET MVC all you need to know are the following :
<%= %>
- Output the result of the evaluation of the input to the response. For example <%= "<div>foo</div>" %>
outputs <div>foo</div>
.<%: %>
- Same as the first one except that it HTML encodes the output. Thus <%: "<div>foo</div>" %>
will output <div>foo</div>
.<% %>
- Evaluates the expression on the server but doesn't output anything in the response. For example you could declare a variable: <% string foo = "foo bar"; %>
that you could use later to output with one of the 2 previous methods<%@ %>
- This is only used to define the Page or Control directives of the view. It also allows you to bring namespaces and assemblies into scope for the given view. For example <%@ Import Namespace="System.IO" %>
will bring the System.IO
namespace into scope.As far as <%#
is concerned, this is not used in ASP.NET MVC. It is a concept called data binding and works only in classic WebForms applications.
<%= ...some text ... %>
: Contains an expression. The result of that expression will have .ToString()
called on it, and the resulting string is output directly.
<%: ...some text ... %>
: Contains an expression. If the expression result is an IHtmlString
, .ToHtmlString()
will be called on it, and the results will be output directly. Otherwise, the result of that expression will have .ToString()
called on it, and the resulting string is escaped before being output.
<@ ...some text ... %>
: Contains a page directive for things like namespaces to be included. This is a compiler directive, and is evaluated when the view is getting compiled (usually the first time the view is invoked).
<% ...some text ... %>
: Contains one or more statements. These statements are executed.
<%# ...some text ... %>
: This is a data-binding expression in ASP.NET WebForms. I don't think it's valid syntax for an MVC View. However, you keep mentioning "user controls", which are not really part of the MVC paradigm, so you might want to reconsider whether this question is really about MVC.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With