4

I'm using the new Routing feature in ASP.NET 4 (Web forms, not MVC). Now I have an asp:ListView which is bound to a datasource. One of the properties is a ClientID which I want to use to link from the ListView items to another page. In global.asax I have defined a route:

System.Web.Routing.RouteTable.Routes.MapPageRoute("ClientRoute",
    "MyClientPage/{ClientID}", "~/Client.aspx");

so that for instance http://server/MyClientPage/2 is a valid URL if ClientID=2 exists.

In the ListView items I have an asp:HyperLink so that I can create the link:

<asp:HyperLink ID="HyperLinkClient" runat="server" 
    NavigateUrl='<%# "~/MyClientPage/"+Eval("ClientID") %>' >
    Go to Client details
</asp:HyperLink>

Although this works I would prefer to use the RouteName instead of the hardcoded route by using a RouteUrl expression. For instance with a constant ClientID=2 I could write:

<asp:HyperLink ID="HyperLinkClient" runat="server" 
    NavigateUrl="<%$ RouteUrl:ClientID=2,RouteName=ClientRoute %>" >
    Go to Client details
</asp:HyperLink>

Now I am wondering if I can combine the route expression syntax and the databinding syntax. Basically I like to replace the constant 2 above by <%# Eval("ClientID") %>. But doing this in a naive way...

<asp:HyperLink ID="HyperLinkClient" runat="server" 
    NavigateUrl='<%$ RouteUrl:ClientID=<%# Eval("ClientID") %>,RouteName=ClientRoute %>' >
    Go to Client details
</asp:HyperLink>

... does not work: <%# Eval("ClientID") %> is not evaluated but considered as a string. Playing around with several flavors of quotation marks also didn't help so far (Parser errors in most cases).

Question: Is it possible at all what I am trying to achieve here? And if yes, what's the correct way?

Thank you in advance!

Slauma
  • 175,098
  • 59
  • 401
  • 420

2 Answers2

13

Use System.Web.UI.Control.GetRouteUrl:

VB:

<asp:HyperLink ID="HyperLinkClient" runat="server"  
    NavigateUrl='<%# GetRouteUrl("ClientRoute", New With {.ClientID = Eval("ClientID")}) %>' > 
    Go to Client details 
</asp:HyperLink>

C#:

<asp:HyperLink ID="HyperLinkClient" runat="server"  
    NavigateUrl='<%# GetRouteUrl("ClientRoute", new {ClientID = Eval("ClientID")}) %>' > 
    Go to Client details 
</asp:HyperLink>
Samu Lang
  • 2,261
  • 2
  • 16
  • 32
  • Great, works fine! I've just changed my markup using this solution. Thank you very much! – Slauma Jun 06 '10 at 19:16
  • 1
    Note: At least in C# you need to use ' and not " for your NavigateUrl. Just copy the examples 1 for 1 and you'll be ok. – scottheckel Jul 18 '13 at 16:45
1

I know it's basically the same as Samu Lan's solution but instead of using .net controls you could use regular HTML anchor control.

<a href='<%# GetRouteUrl("ClientRoute", new {ClientID = Eval("ClientID")}) %>'> 
     Go to Client details
</a>
wegelagerer
  • 3,600
  • 11
  • 40
  • 60