I read this document http://support.microsoft.com/kb/976112
where explains all the embedded code blocks available but I want to combine two of them.
I want to use base <% ... %> embedded code blocks with <%# ... %> data-binding expression
Example I want to add an "If" condition to this code:
<asp:Label ID="lblHello" runat="server" Text="<%# DataBinder.Eval(Container.DataItem, "[\"Txt\"]")%>"></asp:Label>
Regards.
The difference in the <% and <%# is mainly in when they're run (the former at render time, the latter at data binding). As such, it makes no sense to "combine" them.
What you likely want to do, is to run some additional code when data binding to do your if statement. If it's a simple expression, you can just inline it:
<%# MyProperty ? Eval("Txt") : Eval("OtherTxt") %>
If it's more complicated, then it's usually best to just call a code-behind method to do it for you:
<%# MyMethod(Eval("Txt")) %>
Related
I am working on the MVC project in which one of the aspx page also exists for SSRS reports. Here, I have a HTML helper written for returning some multi-lingual text value. So, For all the report labels, I need to call HTML helper extension to get the string text. Is there any way that I can call that method from my aspx page??
Note: I cannot do this from Code behind since all the labels exists in aspx that I do not want to migrate it to code behind.
So far I tried
<%# Import Namespace="Vibrant.HtmlHelperExtension" %>
<asp:Label Text="<%# ReturnKeyValue("Brief") %>" meta:resourcekey="lblBrief" ID="lblBrief" CssClass="label"></asp:Label>
The above one is not able to call the method and I am getting The name 'ReturnKeyValue' does not exist in the current context exception.
This is what I found. Maybe you can try.
http://www.asp.net/mvc/overview/older-versions-1/views/creating-custom-html-helpers-cs
HTML Helper is rendered with <%= %> tags instead of <% %> tags. If you
don't include the equal sign, then nothing gets rendered to the
browser.
I'm developing a front-end part of an application right now, and a question came to my mind.
What is the difference between asp.net special tags:
<%= %>
<%# %>
<%# %>
And if exists another special tag please describe its function.
<%= prints the raw value of the expression within.
This syntax can cause XSS vulnerabilities and should not be used.
<%: prints and HTML-escapes the value of the expression within.
<%# is like <%=, but is used for data-binding
<% executes a block of code and ignores and return values
<%# is used for directives like Page or Imports.
Check the below site Once..You will get an idea
http://naspinski.net/post/inline-aspnet-tags-sorting-them-all-out-(3c25242c-3c253d2c-3c252c-3c252c-etc).aspx
These are some useful special 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. 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
<%: %> Like <%= %> But HtmlEncodes the output (new with Asp.Net 4). 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
<%= %> Code Render Block - For evaluate inline expressions
<%# %> Directive Syntax - Usualy for linking the codebehind and a
asp.net page.
<%# %> Data binding
You can find more information at:
http://msdn.microsoft.com/en-us/library/fy30at8h(v=vs.85).aspx
I've got an ASP Repeater DataBound to a DataTable, and am trying to use a code render block <% %> to do some validation via another function in the project. Basically, if the user isn't an admin, I don't want the first column displayed.
The function is returning correctly, but it still always jumps into the if block. I've tried the same code in another repeater on another page, and it works fine. Any idea why this one is behaving strangely?
<asp:Repeater runat="server" ID="batchesRPT">
<HeaderTemplate>
<table>
<tr> <% if( myProject.myUserRole.IsUserInRole( "ADMIN" ) )
{ %>
<th>Select Batch</th> <% } %>
<th>Batch ID</th>
<th>Batch Date</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<% if( GenKFI.myUserRole.IsUserInRole( "ADMIN" ) )
{ %> <td><%#Eval( "CheckboxVAL" ) %></td> <% } %>
<td><%#Eval( "BatchID" ) %></td>
<td><%#Eval( "BatchDate" ) %></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
UPDATE:
In the code behind previously, the CheckboxVAL would simply be omitted in the non-admin case (so it shouldn't have been a problem, since the if would keep it from getting Eval'ed).
I found this link, and thought maybe it's just evaluating the databinding tags too early. I did some stepping through, and found it would attempt to evaluate <%#Eval( "CheckboxVAL" ) %> first, error out (since CheckboxVAL didn't exist for non-admins), and then go back and evaluate the if statements. I changed it so the non-admin DataTable also contains the CheckboxVAL column, and just leave it empty. Now it will evaluate an empty column, then go back and check the if statements, and not render the first column. So now it works.
This seems like an odd behavior. Does anyone have an explanation for why it's evaluating inside the if statement, then going back later and checking the condition?
Since it seems you've solved your issue, I'll answer about your other question.
Does anyone have an explanation for why it's evaluating inside the if statement, then going back later and checking the condition?
databinding expressions <%# %> are evaluated earlier than inline code <% %>
From MSDN on databinding expressions
Data-binding expressions are resolved when the DataBind method of a
control or of the Page class is called. For controls such as the
GridView, DetailsView, and FormView controls, data-binding expressions
are resolved automatically during the control's PreRender event and
you are not required to call the DataBind method explicitly.
From MSDN on inline code
An embedded code block is server code that executes during the page's
render phase.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
ASP.NET “special” tags
You know how you can embed property value from code-behind in your page by simply using <%= PropertyFromCodeBehind %> in your .aspx?
Well, I only recently discovered that and I can't seem to find any tutorial that would explain this (and related stuff) in more depth (I only know that <%# is used in conjuction with Eval) - probably because I'm using <% for searches.
So, can anybody provide me with more detail explanation of these tags, or give a link to some tutorial that explains all this? I'm interested in anything that can be learned on this subject; somewhere I saw that you can do fancy stuff like <% for ... %>.
Here is a good place to get started.
There are several different syntaxes:
<%$ %> Expression Syntax
<%# %> Data-Binding syntax
<% %> Evaluated Code Blocks
<%= %> Statement and Expression
New to ASP.NET 4 is the HTML encoding syntax (haacked). This is the same as <%= %> except the result is HTML encoded (for non IHtmlString types). The new syntax is intended to replace <%= %>.
<%: %> HTML Encoded output
See ScottGU's post post to get you started.
<% if(Eval("SaveDate") != DBNull.Value){ %>
do magic
<%} %>
gives me error: Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.
I could write : <%# Eval("SaveDate") != DBNull.Value ? do magic
But I need to do lots of html magic in if statement.
I know I should add # in order to use Eval, but not sure about correct syntax.
One solution is to wrap the content in a runat="server" tag with a Visible value, e.g.,
<div runat="server" Visible='<%# Eval("SaveDate") != DBNull.Value %>'>
do magic
</div>
div can be any HTML tag, but <asp:Panel> and <asp:PlaceHolder> could also be used. Note that "do magic" is still databound, so it's not a perfect solution if it contains expensive code or code that could generate an error if Eval("SaveDate") == DBNull.Value.
Note that Visible="false" will omit the tag and all its contents from the generated HTML, this means that it is very different from style="display:none" or style="visible:hidden", so don't worry about that.
But, if your "do magic" is reasonably complex, another rather simple solution (a bit of a hack) is: use a Repeater (or FormView) with its DataSource set to an array of one item (visible) or no items (hidden):
<asp:Repeater runat="server" DataSource='<%# ElementIfTrue(Eval("SaveDate") != DBNull.Value) %>'
<ItemTemplate>
do magic
</ItemTemplate>
</asp:Repeater>
protected IEnumerable ElementIfTrue(bool condition)
{
if (condition)
return new object[] { Page.GetDataItem() };
else
return new object[0];
}
The actual contents of the datasource array is either empty (hidden) or the element you were already binding to. This makes sure you can still call <%# Eval(...) %> inside the ItemTemplate.
With this approach, your "do magic" is a template which will only be executed if DataSource has one or more items. Which is taken care of by ElementIfTrue. It's a bit of a mind bender, but it can save you every once in a while.
As a side note: packing your "do magic" in a user control can also keep the complexity down. You don't really need to change a thing in your HTML/ASP.NET tag mix (<%# Eval("...") %> still works even inside a user control).
I usually add a protected function returning a string to the code-behind to generate the content:
On the page:
<%# Eval("SaveDate") != DBNull.Value ? GenerateContent() : string.Empty %>
In my class:
protected string GenerateContent()
{
return "Hello, World!"
}