Append query string to current page URI

Iman Emran asked on November 18, 2015 15:10

Hello,

I want to append query sting to the current page URI and add it to "href" of <a> tag in my .ascx.

for example the current URI of the page is "http://example.com/products.aspx?lang=en-us&view=list"

so I want to change view=list to view=grid and add the new URI to href in my .ascx like this: <a href="http://example.com/products.aspx?lang=en-us&view=grid" class="grid">grid</a>

and if the url or other query string is changed, it works again.

How can I do that?

Correct Answer

Laura Frese answered on November 18, 2015 20:08

You can get the parameter as Timothy mentioned with QueryHelper.GetString(string key,default val) and you can get the url using System.Web HttpContext.Current.Request.Url.Query

0 votesVote for this answer Unmark Correct answer

Recent Answers


Laura Frese answered on November 18, 2015 17:04

In what context are you trying to do this? Are you doing it programmatically?

0 votesVote for this answer Mark as a Correct answer

Timothy Fenton answered on November 18, 2015 17:38

Hello Iman it looks like you are doing this in some user control, maybe a webpart or control? If so you could just replace your:

<a href="http://example.com/products.aspx?lang=en-us&view=grid" class="grid">grid</a>

with just a regular asp:Literal something like this:

<asp:Literal ID="ltlMyLink" runat="server" EnableViewState="false" />

and then in your code behind you can do your logic for this:

if(QueryHelper.GetString("view", "") == "grid")
{
    ltlMyLink.Text = @"<a href=""http://example.com//products.aspx?lang=en-us&view=list"" class=""list"">list</a>";
}
else
{
    ltlMyLink.Text = @"<a href=""http://example.com//products.aspx?lang=en-us&view=grid"" class=""grid"">grid</a>";
}

of course if you have more than just these two options you should take the value of QueryHelper.GetString("view", "") and maybe do some custom logic with it to get whatever you desired value is to insert in to your URL.

1 votesVote for this answer Mark as a Correct answer

Iman Emran answered on November 18, 2015 19:02

Thanks for your answers.

I want to do that programmatically in a user control but I don't know how to get the current page URL and query string (if it exists!) to set it in href attribute of <a> tag. I want to get full URL and query string to append it view=grid or view=list as query string.

0 votesVote for this answer Mark as a Correct answer

   Please, sign in to be able to submit a new answer.