How to create RouteUrls with databound parameters declaratively?

雨燕双飞 提交于 2019-12-21 17:56:42

问题


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!


回答1:


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>



回答2:


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>


来源:https://stackoverflow.com/questions/2935367/how-to-create-routeurls-with-databound-parameters-declaratively

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!