Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create RouteUrls with databound parameters declaratively?

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!

like image 424
Slauma Avatar asked Dec 09 '22 15:12

Slauma


2 Answers

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>
like image 81
Samu Lang Avatar answered Feb 16 '23 01:02

Samu Lang


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>
like image 34
wegelagerer Avatar answered Feb 16 '23 01:02

wegelagerer