Mr Jeeves
Mr Jeeves

Reputation: 21

How to have a conditional statement within a control tag?

I have a Hyperlink within a Repeater. What I'm wanting 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.

Upvotes: 2

Views: 410

Answers (3)

Magnus
Magnus

Reputation: 46997

<asp:Hyperlink ID="myLink" runat="server" Text="My Link" 
    NavigateUrl='<%# Request.RawUrl.Contains("?") ? Request.RawUrl : 
    Request.RawUrl + "?Id= + Eval("Id") %>' />

Upvotes: 1

Dominic St-Pierre
Dominic St-Pierre

Reputation: 2469

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")) %>' />

Upvotes: 1

Akram Shahda
Akram Shahda

Reputation: 14781

You have to check for two things to be able to build your navigation url correctly:

  1. Does the url contain an Id parameter ??
  2. 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  %>' />

Upvotes: 1

Related Questions