ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
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=<%# Eval("sku") %>">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="https://weblog.west-wind.com/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.
Other Posts you might also like
- Adding minimal OWIN Identity Authentication to an Existing ASP.NET MVC Application
- Map Physical Paths with an HttpContext.MapPath() Extension Method in ASP.NET
- Getting the Client IP Address in ASP.NET Core
- Resolving Paths To Server Relative Paths in .NET Code
- Preventing iOS Textbox Auto Zooming and ViewPort Sizing
The Voices of Reason
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
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
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
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.
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
regards
Ender
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
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
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
<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!
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
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
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
<asp:HyperLinkField DataNavigateUrlFields="systemid,systemname" DataNavigateUrlFormatString="~/ShowEventsForSystem.aspx?SystemID={0}&SystemName={1}"
DataTextField="SystemName" HeaderText="System" />
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
NavigateUrl='<%# this.ResolveUrl("~/" + Eval("Id", "item.aspx?id={0}")) %>'# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
<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);
}
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
<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>
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
NavigateUrl='<%# "myPage.aspx?id=" + HttpUtility.UrlEncode(Eval("Value")) %>'
Bogdan
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
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
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
CommandArgument='<%# string.Format("{0}|{1}",DataBinder.Eval(Container,"DataItem.ClientId"),DataBinder.Eval(Container,"DataItem.Client"))%>'
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
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?
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
Thanks for the snippet it worked perfectly.
Trent
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
Alberto
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
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.
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
Dim photoFile As String
Dim photoPath As String
photoFile = rowView("Picture").ToString.Trim
photoPath = "photos/" + photoFile
imgEmployee.ImageUrl = photoPath
# kpss
NavigateUrl='<%# "myPage.aspx?id=" + HttpUtility.UrlEncode(Eval("Value")) %>'
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
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>
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
<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>
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
for (int i=0;i<5;i++)
{
String key = "b_" + i;
<asp:textBox id='<%#Eval("key")%>' runat="server" />
}
?????.... thanks
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
<ItemTemplate>
<li>
<asp:HyperLink runat="server" NavigateUrl='<%# Eval("ID", "~/Project.aspx?ID={0}") %>'>
<%# Eval("ProjectName") %>
</asp:HyperLink>
</li>
</ItemTemplate># re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
<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.
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
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"
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
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.
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
<asp:HyperLink ID="HyperLink1" runat="server" Text='<%# Eval("ProductName") %>' NavigateUrl='<%# Eval("ProductID", "~\ProductDetails.aspx?ProductID={0}") + "&ProductName=" + Eval("ProductName") %>'> </asp:HyperLink>
# 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.
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
i used
<asp:HyperLink ID="HyperLink1" runat="server" Text="Pay"
NavigateUrl='<%# "Payment.aspx?S=" & Request.QueryString("S") %>' />
but it doesn't work.
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
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
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
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)
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
Thanks for these useful posts tho.
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
<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.
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
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.
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
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)..
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
Many thanks
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
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 :-)
# 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.
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
<%# String.Format("{0:c}", Eval("Price")) %>
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
FYI, you can also nest evals... ie:
<%# Eval("field1", "Value 1 = {0}, "+ Eval("field2", "Value2 = {0}") + "") %>
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
and thank you very much Edgardo
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
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...
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
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
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
<%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>
<%}%>
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
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.
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
<asp:hyperlinkfield DataNavigateUrlFields="myTitle,myMonth,myYear" DataNavigateUrlFormatString="page.aspx?title={0}&month={1}&year={2}" DataTextField="LinkTitle">
Where "myTitle", "myMonth" and "myYear" are my custom fields of a List that i got from my SPDataSource.
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
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
------------------------------------------------------------------------------
# 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";
}
-----------------------------------------------------------------------
# re: ASP.NET ItemTemplates, EVAL() and embedding dynamic values into controls
<asp:HyperLink runat="server" NavigateUrl='<%# Eval("ID", "~/theurl.aspx?id={0}") %>' Text='<%# Eval("Title") %>'/>