سؤال

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().

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top