Safe to use <%# in non-data binding manner - asp.net

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.

Related

How to pass an object from .cs to .aspx

I am a asp .net beginner. I want to use some objects created at Site.Master.cs in Site.Master. Is there an easy way to do it?
I know how to do it in MVC(by using view(the object)). But how can i do it in normal ASP .net web application?
I don't understand what exactly you want to do.
If you want to insert some string into tag's title you can insert the following thing in SiteMaster.master file:
<img src="<%= Page.ResolveUrl("~/") %>images/logo.png">
instead of:
<img src="images/logo.png">
In the first case there will be calculated the path from the root of your application. In the second case there will be relative link. This is because server will CALCULATE the value of Page.ResolveUrl("~") function and will WRITE it in src tag.
You can do the same thing with any other methods, classes if you defined them properly. But I wouldn't recommend you to implement complicated logic in .aspx files (or .master files). Because you can end up with many difficulties with testing and styling such application.
There are other server tags:
<% %> - an embedded code block is server code that executes during the page's render phase. The code in the block can execute programming statements and call functions in the current page class. Description and examples
<%= %> - most useful for displaying single pieces of information. Description and examples
<%# %> - data binding expression syntax. Description and examples
<%$ %> - ASP.NET Expression. Description and examples
<%# %> - Directive Syntax. Description and examples
<%-- --%> - Server-Side Comments. Description and examples
<%: %> like <%= %> - But HtmlEncodes the output (new with Asp.Net 4). Description and examples
Another way: you can use JSON to send some data to the client and then process it with javascript. Take a look at this project.
If the #Page directive in your .aspx file has Inherits="XYZ" where XYZ is the class declared in your .cs file, you can simply add a protected field to your class and assign a value to it. You'll be able to access it in the .aspx file just by using its name.
You can also use HttpContext.Items property to keep objects during a single request:
HttpContext.Current.Items["SavedItem"] = "hello world";
And use it in page:
<%= ((string)Context.Items["SavedItem"]) %>
Any public or protected property or method in Site.Master.cs will be accessible from Site.Master.
but how to invoke c# code in aspx ?
There are several ways, including the <%= %> construction, and databinding syntax.
It would help if you explained what you're trying to achieve.

How does <%$ %> and <%# %> work in ASP.NET?

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

ASP.NET Code Expression, Data Binding, and other Declarative Expressoins

What are the differences in these tags?
<%
<%#
<%=
<%$
More importantly, how do I display a page property using declarative syntax in an ASP.NET control? I'm trying to do this in an ASP.NET control. The task is to set the text of a label but I do not want to do this pro grammatically in the event I want to change the output control. I get an error about server side controls can't contain this syntax. I'm not sure that I need a databound control for what I want to do but that is another option.
Partial answer coming up.
Update
There is a new tag I've seen in ASP.NET 4.5? site
<%:
Partial answer
quoted from Mike Banavige
<% %> An embedded code block is
server code that executes during the
page's render phase. The code in the
block can execute programming
statements and call functions in the
current page class.
http://msdn2.microsoft.com/en-gb/library/ms178135(vs.80).aspx
<%= %> most useful for displaying
single pieces of information.
http://msdn2.microsoft.com/en-us/library/6dwsdcf5(VS.71).aspx
<%# %> Data Binding Expression Syntax.
http://msdn2.microsoft.com/en-us/library/bda9bbfx.aspx
<%$ %> ASP.NET Expression.
http://msdn2.microsoft.com/en-us/library/d5bd1tad.aspx
<%# %> Directive Syntax.
http://msdn2.microsoft.com/en-us/library/xz702w3e(VS.80).aspx
<%-- --%> Server-Side Comments.
http://msdn2.microsoft.com/en-US/library/4acf8afk.aspx
Update:
Okay this appears to work
<asp:Label ID="MyLabel" runat="server" Text='<%# MyProperty%>'></asp:Label>
If I use the eval syntax then I get an error about databound control or I use the <% then I get a server side controls error. Any more color appreciated.. not sure I really understand what is going on.
Perhaps it has something to do with the render phase.
Few more observations:
I can use <%= without databinding and get the property value but can not use it in a server side control without getting error.
If I use <%# in server side control but I'm required to do a Page.Databind.
Interestingly, I can use either <%= or <%# when I want to render text that is not inside a control. Although the latter requires databinding.
The new <%: syntax is explained, also called code expression 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.
http://weblogs.asp.net/scottgu/new-lt-gt-syntax-for-html-encoding-output-in-asp-net-4-and-asp-net-mvc-2
No, server-side controls can't. For example, I have a string property named SkinPath that give me the full App_Themes path to the current theme. I use it in the following way:
<img src='<%= SkinPath %>/Images/myImage.png' />
However, the following doesn't work:
<asp:Image ID='image' runat='server' ImageUrl='<%= SkinPath %>/Images/myImage.png' />
Instead, it renders the src literally in the result <img>.

Inline scripting in ASP.NET

I want to learn advanced and basic things about ASP.NET inline scripting like
<img src="<%= Page.ResolveUrl("~")%>Images/Logo.gif"/>
or
<asp:Label ID="lblDesc" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"Description")%>'></asp:Label>
And so on...
And, what's the difference between <% %> and <%# %> and such stuff?
Where can I find from basic to advanced implementation of those usages?
Check out this article for the specifics of the different inline tag options.
From the article:
<% ... %> -- The most basic inline tag,
basically runs normal code:
<%= ... %> -- Used for small chunks of
information, usually from objects and
single pieces of information
like a single string or int variable:
<%# ... %> -- Used for Binding Expressions;
such as Eval and Bind, most often
found in data controls like GridView,
Repeater, etc.:
<%$ ... %> -- Used for expressions, not code;
often seen with DataSources:
<%# ... %> -- This is for directive syntax;
basically the stuff you see at the top
your your aspx pages like control
registration and page declaration:
<%-- ... %> -- This is a server side comment,
stuff you don't want anyone without
code access to see:
In general, <%#..%> is used for preprocessing a template, such as when databinding, whereby the names of properties of the objects are not known at compile-time. If, for example, you have an ASP.NET Repeater object, and you databind a list of objects to it, this notation is used to pre-populate values that could not be set at any point except during the databind lifecycle.
The other notations, <%..%> and <%=..%> are more standard and you'll see these far more often than the other syntax previously discussed, especially if you use something like ASP.NET MVC instead of ASP.NET Web Forms. The syntax <%..%> executes arbitrary script inline, and nothing more, but allows you to write entire blocks of .NET code such as if statements, while loops, for loops, etc. The syntax <%=..%> is an evaluate-and-write syntax, and is rough equivalent of <% Response.Write([..].ToString()) %>. I.e., <%= myVal %> is the same as <% Response.Write(myVal.ToString()) %>
These syntaxes are basic ASP.NET knowledge.

What are these called <% ... %>? And what ways can they be used in a page

In a .Net web form...
What are these special tags called?
I know of 2: <%-- comment --%> for comments
and <%# used with Eval and Bind #>
So what does the # signify? Are there more?
I know you can put some basic logic and function calls in there but I've never found anything that really describes how that can be used and should be used.
I hope this isn't a duplicate but it's really hard to search for <%#
They're also called bee-stings:
In ASP.Net, what is the difference between <%= and <%#
Server tags. They are called server tags.
Of course there are more.
<%= "string constant" %> - it will output a given string to the HTML output
<%= BO.Customer.GetName () %> - will do the same with the function that returns a string result
<% RenderMyCoolControl %> - without the "=" character, it is supposed that your function will render something to the HTML output using Response.Write
Or you can use that directly: <% Response.Write ("string constant") %>
Hope that helps.
Used for Binding Expressions; such as Eval and Bind, most often found in data controls like GridView, Repeater, etc
Are there more?
Take a look here:
Inline tags
There's a fairly complete list here:
ASP.NET "special" tags
And as the accepted answer on there states, they are "Server Side Scripting Tags"

Resources