I have a Hyperlink
within a Repeater
. What I'm wanting开发者_JS百科 is to set the NavigateUrl
to the page Url and add the query string to the end. I came up with:
<asp:Hyperlink ID="myLink" runat="server" Text="My Link"
NavigateUrl='<%# Request.Url + "?Id= + Eval("Id") %>' />
This works fine. The problem is I want to some how add some logic so if the Request.Url
already contains a query string then not add the id query string part.
How can I do this within the html page? Bear in mind I can't use javascript for this.
You have to check for two things to be able to build your navigation url correctly:
- Does the url contain an Id parameter ??
- Does the url already contain any parameter ??
Use the following:
<asp:Hyperlink ID="myLink" runat="server" Text="My Link"
NavigateUrl='<%# Request.QueryString["Id"] == null ?
(Request.Url.Contains("?") ? Request.Url + "&Id= + Eval("Id") :
Request.Url + "?Id= + Eval("Id")) : Request.Url %>' />
This should work.
<asp:Hyperlink ID="myLink" runat="server" Text="My Link"
NavigateUrl='<%# (Request.Url.ToString().IndexOf("?") > -1 ? Request.Url.ToString() : Request.Url.ToString() + "?Id= + Eval("Id")) %>' />
You might also want to create a protected method on your code behind or if you would need this on multiple places create an Extension Method.
protected string AddIdToRequestUrl(object id)
{
return Request.Url.ToString().IndexOf("?") > -1 ?
Request.Url.ToString() :
Request.Url.ToString() + "?Id=" + id.ToString();
}
<asp:Hyperlink ID="myLink" runat="server" Text="My Link"
NavigateUrl='<%# AddIdToRequestUrl(Eval("Id")) %>' />
<asp:Hyperlink ID="myLink" runat="server" Text="My Link"
NavigateUrl='<%# Request.RawUrl.Contains("?") ? Request.RawUrl :
Request.RawUrl + "?Id= + Eval("Id") %>' />
精彩评论