In the past I have always worked from the code behind page in ASP.NET and emitting all of my markup from that area.
I am now learning MVC and am working in the .ASPX page directly.
The following statements can be written...
<%= Html.Label("Test") %>
<%: Html.Label("Test")%>
<% Html.Label("Test"); %>
The first two emit the word 'Test', while the 3rd doesn't do anything. Yet no errors are thrown.
I seem to recall <%= is shorthand for <% Response.Write("") %>. Is <%: the same shortcut?
I suppose the 3rd statment runs, but simply returns a string that is discarded.
You are right about 1 and 3. 2 does as one, but it html escapes the output.
Related
I'm just wondering, the only difference I know is that the <%= symbols generates any possible html tags that's included with the string your planning to display, while <%: just display what the string exactly look like. If anyone can help me with this, I will greatly appreciate it.
Pretty good explanation from Scott Gu - New <%: %> Syntax for HTML Encoding Output in ASP.NET 4 (and ASP.NET MVC 2)
Excerpt:
ASP.NET applications (especially those using ASP.NET MVC) often rely on using <%= %> code-nugget expressions to render output. Developers today often use the Server.HtmlEncode() or HttpUtility.Encode() helper methods within these expressions to HTML encode the output before it is rendered. This can be done using code like below:
<div>
<%= Server.HtmlEncode(Model.Content) %>
</div>
While this works fine, there are two downsides of it:
It is a little verbose
Developers often forget to call the Server.HtmlEncode method – and there is no easy way to verify its usage across an app
New <%: %> Code Nugget Syntax
With ASP.NET 4 we are introducing a new code expression syntax (<%: %>) that renders output like <%= %> blocks do – but which also automatically HTML encodes it before doing so. This eliminates the need to explicitly HTML encode content like we did in the example above. Instead, you can just write the more concise code below to accomplish the exact same thing:
<div>
<%: Model.Content %>
</div>
The two inline code tags are essentialy the same, the only difference being that <%: %> will automatically use encoding. So this:
<%: myText %>
is equivalent to this:
<%= Html.Encode(myText) %>
The former is recommended.
<%: is HtmlEncoded. Code Nuggets for asp.net
With ASP.NET 4 we are introducing a new code expression syntax (<%: %>) that renders output like <%= %> blocks do – but which also automatically HTML encodes it before doing so.
From Scott Gu blog:
With ASP.NET 4 we are introducing a new code expression syntax (<%:
%>) that renders output like <%= %> blocks do – but which also
automatically HTML encodes it before doing so. This eliminates the
need to explicitly HTML encode content like we did in the example
above. Instead, you can just write the more concise code below to
accomplish the exact same thing:
http://weblogs.asp.net/scottgu/archive/2010/04/06/new-lt-gt-syntax-for-html-encoding-output-in-asp-net-4-and-asp-net-mvc-2.aspx
This question already has answers here:
Closed 10 years ago.
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.
<%# ...some text ... %> is for data-binding expressions; like when you have something like:
<asp:itemtemplate>
<asp:label Text='<%#Eval("Property")%>' .../>
</asp:itemtemplate>
<%= some text %> is basically a shortcut for Response.Write()
<%# some text %> are for application directives; for example when you need to import a namespace: <%# Import namespace="value" %>
I just noticed Stripling warrior answer which compliments this one...
I have been using ASP.NET for years, but I can never remember when using the # and = are appropriate.
For example:
<%= Grid.ClientID %>
or
<%# Eval("FullName")%>
Can someone explain when each should be used so I can keep it straight in my mind? Is # only used in controls that support databinding?
There are a couple of different 'bee-stings':
<%# - page directive
<%$ - resource access
<%= - explicit output to page
<%# - data binding
<%-- - server side comment block
Also new in ASP.Net 4:
<%: - writes out to the page, but with HTML encoded
Also new in ASP.Net 4.5:
<%#: - HTML encoded data binding
<%= %> is the equivalent of doing Response.Write("") wherever you place it.
<%# %> is for Databinding and can only be used where databinding is supported (you can use these on the page-level outside a control if you call Page.DataBind() in your codebehind)
Databinding Expressions Overview
Here's a great blog post by Dan Crevier that walks through a test app he wrote to show the differences.
In essence:
The <%= expressions are evaluated at render time
The <%# expressions are evaluated at DataBind() time and are not evaluated at all if DataBind() is not called.
<%# expressions can be used as properties in server-side controls. <%= expressions cannot.
I was using ASP.NET Web Forms and ASP.NET MVC for some period of time.
So <%= %> in views mean Response.Write(), <%: %> introduced in MVC adds html escaping.
In SqlDataSource control designer generates something like this ConnectionString="<%$ ConnectionStrings:FooConnectionString %>" and in repeater you use <%# Eval("") %> sytax.
My question is what exactly do <%$ %> and <%# %> tags, what methods they traslated into and how do they behave?
<%$ %> is the expression syntax.
There are some built in shortcuts for AppSettings, Resources and ConnectionStrings. You can also write your own.
<%# %> is the databinding expression syntax.
This is used in databound controls to resolve property values from the object being bound.
I clipped this text from a book (I can't remember which book) a while ago as I thought it explained the <%# %> syntax well -
Those of you familiar with classic ASP applications might think that
the <%# %> syntax looks very familiar. It is similar in purpose, but
you need to make sure that you don't confuse the two because doing so
could cause your application to function improperly. Whereas in ASP
(and ASP.NET), the <%= %> syntax causes whatever is inside the
brackets to be evaluated at render time, the <%# %> brackets unique to
ASP.NET are evaluated only during binding. As you will see later in
this section, the page and each bindable control on the page have a
DataBind() method. The expressions contained within the data binding
brackets (<%# %>) are evaluated only when the control's DataBind
method is invoked.
That only answers half your question, but Rob Stevenson-Leggett's excellent answer covers everything else. I just thought I'd add this by way of some further illustration.
I have written a blog post about the different types of expressions available in ASP.NET Web Forms:
Expressions vs. Statements, part 2: ASP.NET Code Block Types (internet archive)
It explains the following expression blocks:
<%$ %>
ASP.NET Expression Syntax, used to bind against application settings, connection strings, and resources.
<%# %>
ASP.NET Data-Binding syntax, only evaluated when calling a data binding method of the control.
<% %>
Code blocks, the code becomes part of RenderMethodDelegate. The code should be statements. Use Response.Write to output something.
<%= %>
Same as above, except the code should be a single expression. It will be wrapped in HtmlTextWrite.Write().
I came across some code where the original programmer is using <%# ... %> in the page where it does nothing related to data binding. It is being used to output a string to the page. Is this safe? Does <%# behave like <%= in this case or <%: ?
Does <%# behave like <%= in this case or <%: ?
Only if the code inside the tag explicitly calls Response.Write() or similar.
The expression between <%# ... %> is evaluated and converted to a string. The result is assigned to a property of a control or, if there is no control, a DataBoundLiteralControl is added. Is it safe? Yes. When the page is accessed for the first time, ASP .Net parses it, generates a new class and compiles it into an assembly, including the code in these blocks.
What is between <%= ... %>, acts the same as the previous, BUT the result is not assigned to any property, it is used by the HtmlTextWriter.Write method, which, btw, returns void so it won't work if you try to use it in a databinding expression.
What about the :
This can be used in the both constructs, : is a safety plus, because the evaluated string is html encoded via System.Web.HttpUtility.HtmlEncode.
So you can use it with the data bindings construct <%#: or with the writer construct <%: (without =).
Tip
Write something in the constructs which will give a compilation error, click on Show Complete Compilation Source, and navigate to that line. The black box is not a black box anymore.