Rick Strahl's Weblog  

Wind, waves, code and everything in between...
.NET • C# • Markdown • WPF • All Things Web
Contact   •   Articles   •   Products   •   Support   •   Advertise
Sponsored by:
West Wind WebSurge - Rest Client and Http Load Testing for Windows

ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls


:P
On this page:

Dealing with complex Eval() expressions inside of ItemTemplate or other data containers always makes me do a double take. Here are a few observations and thoughts on how to handle and possibly improve handling of this feature in the future.

 

So, a typical scenario is embedding controls inside of an item template. The template loops through the datasource and you now want to embed values from the datasource into the child controls of the ItemTemplate.

 

For example:

 

<asp:repeater id="rptSpecials" runat="server">

   <itemtemplate>

       <asp:HyperLink runat="server"

              NavigateUrl='~/item.aspx?sku=<%# Eval("sku") %>'

              Text='<%# Eval("specialhd") %>'/>

   </itemtemplate>

</asp:repeater>

 

Quick what does that give you?

 

Not what you might expect:

 

<a href="item.aspx?sku=&lt;%# Eval(&quot;sku&quot;) %>">West Wind Html Html Help Builder 4.02</a>

 

It's slightly inconsistent isn't it? Text expands just fine with the Eval expression, but the NavigateUrl() doesn't.

 

Now can anybody spot why this is happening?

 

If you change the NavigateUrl expression to:

 

NavigateUrl='item.aspx?sku=<%# Eval("sku") %>'

 

it turns out it actually works. The problem is that that ~/ is causing ASP.NET to call ResolveUrl() which takes the whole string and mucks up the string. Take the ~ out and ASP.NET no longer calls ResolveUrl and it actually works.

 

Now it seems to get this to work anyway is this:

 

<asp:HyperLink runat="server"

     NavigateUrl='<%# Request.ApplicationPath %>/item.aspx?sku=<%# Eval("sku") %>'

     Text='<%# Eval("specialhd") %>'/>

 

But that results in the following error:

 

Compiler Error Message: CS1040: Preprocessor directives must appear as the first non-whitespace character on a line

Source Error:

 

 

Line 7:        <tr>

Line 8:           <td valign="top">

Line 9:              <asp:HyperLink runat="server"

Line 10:                  NavigateUrl='<%# Request.ApplicationPath %>/item.aspx?sku=<%# Eval("sku") %>'

Line 11:                  Text='<%# Eval("specialhd") %>'/>


Source File: c:\projects2005\wwstore\UserControls\SpecialsListing.ascx    Line: 9

 

If you add a character (say a<%# …%> then it works). I have no idea why this would be a problem for ASP.NET to parse, all I know is it doesn't work.

 

I suspect there's a bug in the ASP.NET parser in this situation, especially for the first case where apparently ASP.NET is calling ResolveUrl before it's doing the eval on the embedded string.

 

With all this sort of headache ultimately it's easier to just write out the HREF manually:

 

<a href="<%# Request.ApplicationPath %>"/item.aspx?sku=<%# Eval("sku") %>">

 <img src="<%# Request.ApplicationPath %>/itemimages/sm_<%# Eval("Itemimage") %>" />
</a>

 

I bring this up because this sort of thing seems to happen quite frequently. I really wish there was better support for assigning dynamic values. Maybe something using FormatStrings that could be replaced with some dynamic properties:

 

NavigateUrl="~/MyPage/MyPage?Id={0}" Text="SomeText {1}"

Parameter0="<%# Eval("Sku") %>

Parameter1="<%# Eval("Company") %>"

 

It may seem like this is overkill but I find myself running into situations quite frequently where the single string delimiter makes it near impossible to create a clean expression in script code. The above solution would solve that problem in all situations because you'd eliminate the need to nest the Eval expression with its string delimiter and you get back the use of two string delimiters.

 

There are workarounds today, they're just not quite as declarative. The above behavior could be simulated with something like this:

 

NavigateUrl='<%# this.ResolveUrl("~/" + string.Format("item.aspx?sku={0}",Eval("sku")) %>'

 

Still that doesn't really get around the string delimiter issue. Try this:

 

NavigateUrl='<%# this.ResolveUrl("~/" + string.Format("onclick=DoItem('{0}');",Eval("sku"))%>'

 

There's the problem with the string nesting. Remove the Eval() completely from this expression would fix this problem.

 

Today my workaround for complex expressions that just don't want to work is to create a method on the page or control that returns the value which is workable, but not a solution the average novice will think of.

 

<asp:HyperLink runat="server"

     NavigateUrl='<%# this.GetItemUrl( Eval("sku") as string ) %>'

     Text='<%# Eval("specialhd") %>'/>

 

where GetItemUrl() simply does all of the formatting for the URL.


The Voices of Reason


 

Edgardo
April 27, 2006

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

Why are you complicating things so much? you're using asp.net 2.0 right? In the case of URLs you can simply do:

<asp:HyperLink runat="server" NavigateUrl='<%# Eval("ID", "~/theurl.aspx?id={0}") %>' Text='<%# Eval("Title") %>'/>

scottgu
April 27, 2006

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

The reason you were getting a syntax error is because <%# Eval() %> is a databinding expression and must evaluate to the property. You can't concatinate it with another string outside of the eval expression.

So you couldn't do this:

property='foo<%#Eval("value")'

but you could do the concatination like this:

property='<%# 'foo' + Eval("value")%>'

Edgardo's solution using the format expression above is probably the most elegant one though.

Hope this helps,

Scott

Rick Strahl
April 27, 2006

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

Hmmm... ok, so I'm learning something new here <g>... It never really occurred to me that the <%# %> needs to be the exclusive value in the attribute - I just figured it would evaluate inside of the content simlar to the way it works inside of literal template.

Great! Actually this will simplify a few things - thanks to both Edgardo and Scott for clarifying.

Now that still doesn't solve the problem if you for whatever reason need to generate something with the single quote (') in it because of the string nesting.

Miki Watts
April 29, 2006

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

You might want to check out pagemethods.com, it's a way to work with page references in a structured, object oriented way. I find that for me it solved most if not all of those problems with the string delimiters.

David
May 03, 2006

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

Edgardo, you the man! Don't understand it (I'm kinda new) but it works sweet. Cheers.

Ender
May 04, 2006

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

Edgardo, how to pass two parameters in Your exmaple (f.ex. : ID and Title)?

regards
Ender

Jam
May 17, 2006

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

hmmm...

any idea how write an expression that will correctly parse something like this one that won't?

<asp:ImageButton ImageUrl='<%# Eval("DirectoryVirtualPath" %><%# Eval ("ImageFileName") %>' ID="id" runat="server" />

where "DirectoryVirtualPath" is '../folder/'
& where "ImageFileName" is 'file.jpg'

thanks

Jam
May 17, 2006

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

By the way it's probably relevant to mention that this ImageButton is in a gridview column which is why I'm finding it a bit tricky.

<asp:GridView ...>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ImageUrl='<%# Eval("DirectoryVirtualPath" %><%# Eval ("ImageFileName") %>' ID="id" runat="server" CommandName="Select" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:Gridview>


Thanks!

Irfan
June 15, 2006

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

Ender,

I would suggest you go forward with using the option suggested by scottgu. That should solve your purpose of passing 2 or more parameters.

Thanks

ScottS
September 18, 2006

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

I had a similar problem with this stuff, I was trying to put a hyperlink as a colum of a datagrid. Fortunately someone put me onto the DataNavigate parts of this... code below works a treat
<asp:HyperLinkField DataNavigateUrlFields="systemid,systemname" DataNavigateUrlFormatString="~/ShowEventsForSystem.aspx?SystemID={0}&amp;SystemName={1}"
DataTextField="SystemName" HeaderText="System" />

# DotNetSlackers: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls


Coskun SUNALI (MVP)
December 04, 2006

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

It is better this way, without having to call string.Format method:

NavigateUrl='<%# this.ResolveUrl("~/" + Eval("Id", "item.aspx?id={0}")) %>'

Noam
December 26, 2006

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

I used the following:

<asp:HyperLink id="category"
NavigateUrl='<%# Utils.FormatUrl(this, "~/client/subCat.aspx?CatID={0}&CatName={1}", Eval("Id"), Eval("CName")) %>' runat="server" Text='<%# Eval("CName") %>' />

and the method:

public static string FormatUrl(System.Web.UI.Page page, string url, params object[] args)
{
if (url.StartsWith ("~/"))
{
url = url.Replace("~/", page.Request.ApplicationPath + '/');
}

return string.Format(url, args);
}

TraceyM
January 05, 2007

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

So how could I get the following into NavigateUrl using VB? I'm editing a itemTemplate within a FormView control, not familiar with C#. Thank you

<a href='http://www.mapquest.com/maps/map.adp?countrycode=250&country=US&address=<%# Eval("address") %>&city=<%# Eval("city") %>&state=<%# Eval("state") %>&zipcode=<%# Eval("zip") %>&addtohistory=&submit.x=49&submit.y=13'>Map</a>

Bogdan
March 06, 2007

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

Have you tried this?

NavigateUrl='<%# "myPage.aspx?id=" + HttpUtility.UrlEncode(Eval("Value")) %>'

Bogdan

Nicolas
April 12, 2007

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

Hello everybody !

Interesting article, but i have a question :

Can the "eval" method be applied with asp menus ? In other words, how, with asp menus, can we dynamically set the "selected" property of a menu item with a querystring value ? I try several things i read here but nothing works.

Page call :
http://server/mymenupage.aspx?selectedmenu1=true
or
http://server/mymenupage.aspx?selectedmenu1=false

Page partial code :

...
<% selval1=request.querystring("selectedmenu1")%>

//declaration of menu
<asp:Menu...
...
//Menu Item i want to select
<Items>
<asp:MenuItem Text="menuitem1" Value="menuitem1" Selected='<%# eval("selval1")%>' ></asp:MenuItem>
...

Any idea ?

Sorry for my poor english.

Nicolas

XPAZ
June 20, 2008

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

An easy way to stack data into arguments or control prperties in a control

CommandArgument='<%# string.Format("{0}|{1}",DataBinder.Eval(Container,"DataItem.ClientId"),DataBinder.Eval(Container,"DataItem.Client"))%>'

jose
June 25, 2008

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

hi.

who to use the value in a function. like this:

<script language="VB" runat="server">
Public Function o_n_m(ByVal id_foro As String) As String
Dim bd As New BDD_MySQL
Dim dt As System.Data.DataTable = Nothing
bd.CadenaConexion = Session("CadenaIntranet")
dt = bd.Consultar("select count(id_foro) from foro_tiene where id_foro=" + id_foro)
Return dt.Rows(0).Item(0).ToString()
End Function
</script>

...

<td align="center"><%#Response.Write(o_n_m(Eval("id_foro")))%></td>

does anybody knows how to use the values of eval as parameter in a function? or other way to solver this?

Trent
June 26, 2008

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

Edgardo,

Thanks for the snippet it worked perfectly.

Trent

Alberto B
July 16, 2008

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

Well done, Edgardo. I spent an hour to try to find a solution. It worked really well ;-)

Alberto

James
July 25, 2008

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

Having a similar issue. Seems like it should be simple, but new to me. I would like the image to change based on the selected record. The image file name is in a database.

The correct path should be "photos/(name of file here)". I am using the following code with no luck. Any help would be great.

<asp:Image ID="imgEmployee" ImageUrl='photos/<%# Eval("filename")%>' runat="server" Height="201px" Width="175px" />

I tried some of ideas from above but struck out.

James
July 25, 2008

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

Was able to set the path with code. See example.

Dim photoFile As String
Dim photoPath As String
photoFile = rowView("Picture").ToString.Trim
photoPath = "photos/" + photoFile

imgEmployee.ImageUrl = photoPath

kpss
July 29, 2008

# kpss

Have you tried this?

NavigateUrl='<%# "myPage.aspx?id=" + HttpUtility.UrlEncode(Eval("Value")) %>'

KG
August 19, 2008

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

The solution given by ScottS is too good. Works like a charm.. Good going buddy!!

Janis
November 26, 2008

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

This is the closest I've come to for find what SHOULD be a simple solution. My issue is getting the value of a selected item from a dropdownlist into the querystring. The name of the DDL is "DDL_SupvDelegated", the DataValueField is "SupvUserID". Below it is the MenuItem with 3 subitems, each going to a different URL. I simply want to get the dang SupvUserID VALUE into the querystring! I've wasted a lot of time with numerous solutions so for anybody who can give me the answer, I will buy a box of Dunkin Donuts!

Code:

<tr>
<td>
<asp:Panel ID="Panel_SupvDelegated" runat="server" Visible="false" Width="100%">
<table width="100%">
<tr>
<td class="title2" colspan="2">Select supervisor for:
<asp:DropDownList ID="DDL_SupvDelegated" runat="server"
DataSourceID="SqlDataSource_SupvDelegated" DataTextField="SupvName"
DataValueField="SupvUserID" >
</asp:DropDownList>
</td>
</tr>
</table>
</asp:Panel>
</td>
</tr>
<tr>
<td>
<asp:Menu ID="Menu_SupvDelegated" runat="server" Orientation="Vertical" Visible="false">
<Items>
<asp:MenuItem Text="Delegated Functions" Value="Contracts">
<asp:MenuItem Text="Contract Expense Review" Value="ContrExpRev" NavigateUrl='ClinExpDeleg8.aspx?SID=<%# Eval("DDL_SupvDelegated.SelectedValue") %>'></asp:MenuItem>
<asp:MenuItem Text="Staff Note Review" Value="StaffNoteRev" NavigateUrl=""></asp:MenuItem>
<asp:MenuItem Text="Timesheet/Leave Requests Review" Value="TimeLRrev" NavigateUrl=""></asp:MenuItem>
</asp:MenuItem>
</Items>
<StaticItemTemplate>
<asp:HyperLink runat="server" NavigateUrl='<%# Eval("NavigateURL") %>'
Text='<%# Eval("Text") %>' ID="selected"></asp:HyperLink>
</StaticItemTemplate>
<levelsubmenustyles>
<asp:submenustyle CssClass="FooterStyle2" Font-Underline="False"/>
<asp:submenustyle backcolor="#404040" CssClass="title2" Font-Underline="False"/>
</levelsubmenustyles>
</asp:Menu>
</td>
</tr>

Jason M
February 25, 2009

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

Another option:
<asp:HyperLink ID="myHyperLink" runat="server" NavigateUrl='<%# "/page.aspx?type=" + DataBinder.Eval(Container.DataItem,"type") + "&year=" + DataBinder.Eval(Container.DataItem,"years") %>'>
<%# Eval("Years") %></asp:HyperLink>

sebenscen
February 27, 2009

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

Can i do this:
for (int i=0;i<5;i++)
{
String key = "b_" + i;
<asp:textBox id='<%#Eval("key")%>' runat="server" />
}

?????.... thanks

Ryan Pritchard
March 13, 2009

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

This is probably the easiest way to accomplish this. You may already know because this article was written a while ago.
<ItemTemplate>
    <li>
        <asp:HyperLink runat="server" NavigateUrl='<%# Eval("ID", "~/Project.aspx?ID={0}")  %>'>
        <%# Eval("ProjectName") %>
        </asp:HyperLink>
    </li>
</ItemTemplate>

Rama
April 03, 2009

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

what is wrong with this?

<td><% if(# Eval("Path") == null){%><asp:LinkButton CommandArgument='<%# Eval("ID") %>' ID="btnin" OnClick="btnin_Click" runat="server" PostBackUrl="walkin.aspx?<%# Eval("ID") %>" Text="add file"></asp:LinkButton><%}
                      else {%>file: <%# Eval("Path"); }%></td>


thanks.

Electric_Lettuce
April 05, 2009

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

Hi Rama,

I think your PostBackUrl property is malformed. The syntax looks wrong and you aren't specifying a parameter name for the querystring that you are generating. Maybe this would work:
PostBackUrl='<%# "walkir.aspx?ID=" & Eval("ID") %>'


The resulting querystring would look something like this: "walkir.aspx?ID=7"

Electric_Lettuce
April 05, 2009

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

I had a problem trying to create an asp:hyperlink control that would generate a querystring with multiple parameters. It took me a while but I figured it out. I wanted to share my findings in case someone else has similar issues.

I was using a DataList that contained a HyperLink control. I needed to generate a querystring, for the HyperLink control's NavigateUrl property, which would pass both the ProductID and ProductName to a page called ProductDetails.aspx page. Also, a requirement was that all links had to use relative paths. So the url had to be resolved.

The following code shows how I accomplished this:

<asp:HyperLink ID="HyperLink1" runat="server" Text='<%# Eval("ProductName") %>'
 NavigateUrl='<%# Eval("ProductID", "~\ProductDetails.aspx?ProductID={0}") & "&ProductName=" & Eval("ProductName") %>'>
</asp:HyperLink>


Example:

ProductName is 'Funky Widget' and it's ProductID is '7'

Would generate the following querystring:
hxxp://HostName/WebsiteDirectory/ProductDetails.aspx?ProductID=7&ProductName=Funky Widget

I hope this helps somebody save some time and headaches.

McMohan
April 15, 2009

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

I think navigateURL for multiple parameters need to be passed with "+" instead "&" to avoid compilation error.


<asp:HyperLink ID="HyperLink1" runat="server" Text='<%# Eval("ProductName") %>'
 NavigateUrl='<%# Eval("ProductID", "~\ProductDetails.aspx?ProductID={0}") + "&ProductName=" + Eval("ProductName") %>'>
</asp:HyperLink>

Electric_Lettuce
April 17, 2009

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls


For VB: both '&' and '+' will work. (Or at least it works in .NET 2.0).

Maybe '&' has become deprecated and '+' is the way to go; I haven't looked into it, however.

Fenil
April 25, 2009

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

i want to strictly pass the querystring from aspx page & not from code behind then how to do it?

i used

<asp:HyperLink ID="HyperLink1" runat="server" Text="Pay"
NavigateUrl='<%# "Payment.aspx?S=" & Request.QueryString("S") %>' />

but it doesn't work.

Frederik
April 28, 2009

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

Why not a custom control? (asp.net 3.5 didn't have time to test on other platforms)

Namespace CustomControls
    Public Class Hyperlink
        Inherits WebControls.HyperLink
        Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
            Dim originalNavigateUrl As String = NavigateUrl
            NavigateUrl = String.Format(NavigateUrl, GetParameterArray)
            MyBase.Render(writer)
            NavigateUrl = originalNavigateUrl
        End Sub
        Private Function GetParameterArray() As String()
            Dim parameters As New List(Of String)
            For i As Integer = 0 To 20
                Dim parameterName As String = "Parameter" & i
                If Attributes.Item(parameterName) IsNot Nothing Then
                    parameters.Add(Attributes.Item(parameterName))
                Else
                    Exit For
                End If
            Next
            Return parameters.ToArray()
        End Function
    End Class
End Namespace


<CustomControl:Hyperlink 
ID="Hyperlink1" 
runat="server" 
Text="click here" 
Parameter0='<%#Eval("name")%>' 
Parameter1='<%#Eval("id")%>' 
Parameter2="foo"
NavigateUrl="/pages/{0}/{1}/default.aspx?id={2}"  />


Make sure to register your control in web.config

Frederik
April 28, 2009

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

@ Fenil

In a databindle control (eg. repeater, gridview, detailsview, ...) it could work like this, using the custom control I posted before:

<CustomControl:Hyperlink 
ID="Hyperlink1" 
runat="server" 
Text="click here" 
Parameter0='<%#Request.QueryString("S")%>' 
NavigateUrl="Payment.aspx?S={0}">

Allthough make sure you sanitize your input first. (as in filter your QueryString first)

Aaron
August 02, 2009

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

I think I am getting addicted to this web site. Whatever I look for,Google leads me here :)

Thanks for these useful posts tho.

QQ
August 14, 2009

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

Solution by Edgardo April 27, 2006 @ 5:12 pm works perfect for me. Thanks!

Jayson Ragasa
August 28, 2009

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

This works for me

<asp:TemplateField ItemStyle-HorizontalAlign="Center">
                <ItemTemplate>
                    <asp:HyperLink ID="hlView" runat="server" NavigateUrl='<%# string.Format("LookupModify.aspx?ParentID={0}&LookupPK={1}", Request.QueryString["ParentID"].ToString(), Eval("ID")) %>' Text="Edit"></asp:HyperLink>
                </ItemTemplate>
                <ItemStyle HorizontalAlign="Center"></ItemStyle>
            </asp:TemplateField>


But am not sure why the intellisense was not showing while typing in the NavigateUrl property .. though that really works.

Barry Pekin
September 10, 2009

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

So many ways to skin a cat, eh?

This article didn't seem to have the answer, but all of these comments did. I had two variables to integrate with the URL, so I did:

<%# BuildMyURL(Eval("Arg1"),Eval("Arg2")) %>


In the page, I have a function BuildMyURL that accepts the two arguments and returns a string that represents the URL, which, by the way, is ok with having "~/" at the beginning so that the link is relative to the root of the application.

jp
September 28, 2009

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

I tried for a bit and came up with this solution for redirection from a indexed search page...

Thought you'd like to know this:

<asp:HyperLink
ID="HyperLink1"
runat="server"
NavigateUrl='<%#"http://websitename.com/folder/"+Eval("Filename")%>'
Text='<%# Eval("Filename") %>'/>
</td>

Pay close attention to the double quotes for the url prefix... single quotes don't work as advertised in the scottgu post (2nd from top)..

BobbyD
October 13, 2009

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

Many thanks, this article and the many solutions in it saved me hours of searching.

Many thanks

Sibel Kendibaşına
February 10, 2010

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

thank you many many times. it was very useful for me :))

Mike Kingscott
February 26, 2010

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

Best place this on here, going off Scott Gu's comments and addressing the need to write methods as suggested by Barry Pekin, which I have used.

Here's a hyperlink with one NavigateUrl databound item, and two in the text field, with formatting:

<li><asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# Eval("JobID", "~/contractor/editjobreg.aspx?jobid={0}") %>' Text='<%# "<strong>" + Eval("JobReference") + "</strong> - " + Eval("DwellingAddress.AddressSingleLine") %>'></asp:HyperLink></li>


Hope this helps someone, I'll be adding this to my blog at some point and obviously H/T-ing this thread and site.

Kind regards,

Mike K.

PS I looooove long lines of code :-)

Hardik Shah
March 09, 2010

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls


Quite well written and supported with facts and issues commonly faced by .Net guys like us. The only question remains for me is how can we use the Eval function outside Controls in the .aspx page.

DotNetKicks.com
March 21, 2010

# ASP.NET ItemTemplates, EVAL() and embedding dynamic values into contro

You've been kicked (a good thing) - Trackback from DotNetKicks.com

Ray Wampler
March 21, 2010

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

Great article. Here's how you would use the string format function with Eval:

<%# String.Format("{0:c}", Eval("Price")) %>

HC
April 07, 2010

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

Hey guys,
FYI, you can also nest evals... ie:
<%# Eval("field1", "Value 1 = {0}, "+ Eval("field2", "Value2 = {0}") + "") %>

Sekar
June 01, 2010

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

thank you very much for person, who was asked such a question,
and thank you very much Edgardo

Saurabh
July 06, 2010

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

Can we use Eval mathod to bind the Items inside a List; e.g. the list is like this

ParentClass{

public ChildClassList = new ChildClassList();
}

ChildClassList List<ChildClass>{
public ChildClassList();
}

ChildClass{
public string ChildName;
public string ChildAge;
}
And in binding I am doing gridView.DataSource = objParentClassList;

Now in Eval mathod I want <%# Eval("ChildClassList.ChildName") %>

but I am getting error as "DataBinding: 'ChildClassList' does not contain a property with the name 'ChildName'."

Any help will be greatly appreciated...

David McReynolds
August 11, 2010

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

Great article, finally found out how to get my link to work!

Søren
September 12, 2010

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

Interesting article and long following discussion. I stumbled across this problem today and, as many others before me, found my way here via Google. Just as much as Rick didn't know the finer plumbings of Eval, I also first made a solution like he originally suggested. But I got curious about this elusive Eval and how it works. Anyway, Rick, thanks for many good articles scattered many places in .NET forums. You've given me good ideas more than once :-)

Anyway...

Basically Eval will find the column name in the datasource and return an "object" (yes, type is object) if it finds it. The expression is then evaluated using normal rules, i.e. in most of the above cases the object will be applied its ToString() method and then inserted.

For example, in:

<asp:HyperLink ID="HyperLink_Email" runat="server"
Text='<%# Eval("Email") %>'
NavigateUrl='<%# "mailto:" + Eval("Email") %>' />


the NavigateUrl will form a nice mailto-link as the first part of the expression evaluates to a string and the "string" object overrides the + operator simply calling the supplied object's ToString() method, thereby calling ToString() on Eval()'s returned value automatically.

Same goes for this other (sometimes useful) example:

<asp:Literal ID="Literal_LastLogin" runat="server"
Text='<%# DateTime.Parse(Eval("LastLogin").ToString()).ToShortDateString() %>' />


This time, I call ToString() myself before calling DateTime.Parse on the result. The above is for illustration, since usually you would receive a DateTime object already, so the following works just as well (and is a bit more elegant):

<asp:Literal ID="Literal_LastLogin2" runat="server"
Text='<%# ((DateTime)Eval("LastLogin")).ToShortDateString() %>' />


In this last example I am simply casting the object returned from Eval to the type it really is, and then calling methods on it as usual.

The main point is: Don't forget that Eval returns an object (of type object), that you may need to cast to make it digestible.

Cheers
Søren
http://sugarsoft.com

Courtney
September 15, 2010

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

Hi all, im trying to load the ID from an inline statement but it not working. is this possible or something long these lines? I would prefer to do this inline as im making large custom tables that dont go well into repeaters.

<%foreach (laptopprogram.Student s in Students)
{
String ID = s.StudentID;
%>
<tr>
<td>
<asp:ImageButton ImageUrl='<%# Eval("ID", "GetPhoto.aspx?ID={0}")%>' Width="75px" OnCommand="image_Command" CommandArgument='<%# Eval("ID")%>' runat="server" />
</td>
<%}%>

antmx
November 18, 2010

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

I sometimes use the databound control's ItemDataBound event in the code-behind file when there's something complex to be rendered in the item template:

in the .aspx/.ascx:

<asp:repeater id="repData" runat="server" OnItemDataBound="repData_ItemDataBound">
   <itemtemplate>
       <asp:HyperLink runat="server" Id="hyperlink1"
              NavigateUrl="set in ItemDataBound event handler" 
              Text="set in ItemDataBound event handler" />
   </itemtemplate>
</asp:repeater>


in code-behind:

Protected Sub repData_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs)
   
   ' DataItem will be null if header/footer template
   If e.Item.DataItem Is Nothing Then Return
 
   ' Get object being bound, cast to specific type
   Dim newsItem = DirectCast(e.Item.DataItem, NewsItem)
 
   ' Get control(s) in item template, cast to specific type
   Dim hyperlink1 = DirectCast(e.Item.FindControl("hyperlink1"), HyperLink)
 
   ' Set control properties from data object
   hyperlink1.Text = String.Format("{0} {1:d}", newsItem.Title, newsItem.PublishDate
   hyperlink1.NavigateUrl = newsItem.Url
 
End Sub


It's a lot more work, but helps seperate markup from code.

vijay odedra
February 04, 2011

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

i want to convert floating value like 4.0000 into 4.00 by using eval..hows it possible??pls reply fast..thanks..

Edisour
February 10, 2011

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

I use the next code to solve this problem:

<asp:hyperlinkfield DataNavigateUrlFields="myTitle,myMonth,myYear" DataNavigateUrlFormatString="page.aspx?title={0}&amp;month={1}&amp;year={2}" DataTextField="LinkTitle">
.

Where "myTitle", "myMonth" and "myYear" are my custom fields of a List that i got from my SPDataSource.

yousaid
March 09, 2011

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

Well, I have same problem with a twist.
I am using Query Extender control and need to archieve same results as the thread here.
Here is my Question posted on Asp.net forum: http://forums.asp.net/p/1661648/4335581.aspx#4335581
--------------------------------------------------------------------
I have a user control, named productslist.ascx.
On pruductslist.ascx, I am using Entity Datasource and a QUERY EXTENDER and LISTview.

I have a page Defualt.aspx. On Defualt.aspx, I have a TEXTBOX with a SUBMIT button for searching the site.
Everthing works fine so far, AS LONG as the results of the Search is posted back to Default.aspx.

What I want is for the results of the search to be posted on a different page.
So I created a new page, Results.aspx and set the postback url to it.
What I want is that when a user clicks the Submit button, after entering a search string, the text the entered is used to execute the query on Productslist.ascx and the results displayed on RESULTS.ASPX. Again, everything works fine as long as the results are posted on same page hosting the usercontrol, BUT I want the postback url to be a different page.
I am coding in VB and VS 2010.
cheers,
yousaid
------------------------------------------------------------------------------

Nilesh Umaretiya
April 01, 2011

# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls

---------------------------------------------------------------------------------------
.aspx file
<asp:TemplateField HeaderText="|| Status ||">
<ItemTemplate>
<asp:Image ID="imgGreenAct" ImageUrl='<%# GetImage(Convert.ToString(DataBinder.Eval(Container.DataItem, "truck_status")))%>' AlternateText='<%# Bind("truck_status") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
----------------------------------------------------------------------------------------
.aspx.cs file
public string GetImage(string status)
{
if (status=="Active")
return "~/images/green_acti.png";
else
return "~/images/red_acti.png";
}
-----------------------------------------------------------------------

West Wind  © Rick Strahl, West Wind Technologies, 2005 - 2024