tags:

views:

380

answers:

4

I'm writing an asp.net user control. It has a property FurtherReadingPage, and controls: ObjectDataSource and a Repeater bound to it. Inside the Repeater I would like to display a hyperlink with a href property set to something like FurtherReadingPage + "?id=" + Eval("Id") and I don't know how to do it inside html code. I can use <% Eval("Id") %> or <% Response.Write(FurtherReadingPage + "?id=") %> alone but I don't know how to mix them.

A: 

Try this (example as link): <a href='<%=FurtherReadingPage %>?id=<%# Eval("Id") %>'>My link</a>

Sergio
This mixes <%= and <%#, which will create problems in most circumstances. <%= won't work inside a Repeater and <%# won't work unless DataBind() is called.
Keith
@Keith: You are wrong. I just tried <%= "Test" %> inside a repeater to double check and it works ok. <%# only works with Databind() which is the case.
Sergio
Sorry, yes, <%= can work in repeaters, depending on the control hierarchy above not containing any collection style controls. Basically <%= FurtherReadingPage %> will sometimes work in a repeater, while <%# FurtherReadingPage %> always will.
Keith
+1  A: 

Try this:

<%#String.Format("{0}?id={1}",FurtherReadingPage, Id)%>
Saul Dolgin
+2  A: 

You can do it like this -

<asp:Hyperlink runat="Server" ID="hlLink" NavigateUrl='<%# FurtherReadingPage + "?Id=" + DataBinder.Eval(Container.DataItem, "Id")  %>' />
Kirtan
+2  A: 

You have a couple of different tags:

<% executes the code inside:

<% int id = int.Parse(Request["id"]); %>

<%= writes out the code inside:

<%=id %> <!-- note no ; -->

<!-- this is shorthand for: -->
<% Response.Write(id); %>

Both of these break up the normal flow when rendered on a page, for instance if you use them in a normal Asp.net <head runat="server"> you'll get problems.

<%# databinding:

<%# Eval("id") %>

This allows you to specify the bindings for controls that Asp.net WebForms render as a collection (rather than the literal controls that you can use <%= with), for instance:

<!-- this could be inside a repeater or another control -->
<asp:Hyperlink runat="server" ID="demo" 
     NavigateUrl="page.aspx?id=<%# Eval("id") %>" />

<%  //without this bind the <%# will be ignored
    void Page_Load( object sender, EventArgs e ) {
        demo.DataBind(); 
        //or
        repeaterWithManyLinks.DataBind(); 
    } 
%>

For your specific case you either:

  • Use a repeater and <%# Eval(...) %> with repeater.DataBind();

or

  • Use a foreach loop (<% foreach(... %>) with <%= ... %>
Keith