How to create RouteUrls with data binding parameters declaratively?

I am using the new routing feature in ASP.NET 4 (web forms, not MVC). Now I have an asp: ListView bound to a data source. One of the properties is ClientID , which I want to use to link from ListView elements to another page. In global.asax I defined a route:

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

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

In the ListView element, I have asp: HyperLink so that I can create a 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 RouteName instead of hardcoded route using the RouteUrl expression. For example, with the 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'm wondering if I can combine the syntax of the route expression and the data binding syntax. Basically, I like to replace the constant 2 above with <%# Eval("ClientID") %> . But doing it naively ...

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

... does not work: <%# Eval("ClientID") %> not evaluated, but treated as a string. The game with several options for quotes has also not helped so far (Parser errors in most cases).

Question: Is it possible at all, what am I trying to achieve here? And if so, what is the right way?

Thank you in advance!

+4
source share
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> 

FROM#:

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

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

 <a href='<%# GetRouteUrl("ClientRoute", new {ClientID = Eval("ClientID")}) %>'> Go to Client details </a> 
+1
source

Source: https://habr.com/ru/post/1311294/


All Articles