How to create a dynamic hyperlink in datalist

2019-09-17 18:37发布

问题:

I am using a datalist to display a summary of news stories stored in a SQL Server database.

<asp:DataList ID="DL_NewsSummary" runat="server" DataKeyField="newsItemId" 
    DataSourceID="DS_NewsSummary">
    <ItemTemplate>
        <h3>
            <asp:HyperLink ID="headlineLink" runat="server" Text = '<%# Eval("headline") %>' NavigateUrl="#" />
        </h3>
        <asp:Label ID="dateLabel" runat="server" Text='<%# Eval("date") %>' />
        <br />
        <asp:Label ID="introLabel" runat="server" Text='<%# Eval("intro") %>' />
        <hr />      
    </ItemTemplate>
</asp:DataList>

When the user clicks the headline hyperlink they should be taken to the full story on a separate page, news.aspx. This page will get the newsItemId from the querystring and populate the page with the story associated with that id e.g. news.aspx?newsItemId=1.

However when I change the navigateUrl field to the following I get a server tag not well formed error.

<asp:HyperLink ID="headlineLink" runat="server" Text = '<%# Eval("headline") %>' NavigateUrl="news.aspx?newsItemId=<%# Eval("newsItemId") %>" />

Any help is greatly appreciated

回答1:

Try this:

NavigateUrl='<%# "news.aspx?newsItemId=" + Eval("newsItemId") %>'