开发者

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开发者_JAVA百科,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!


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>


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜