Alex
Alex

Reputation: 9720

How to add one parameter to current url in c#

I have 2 links

 <li class="active">
  <a href="<%#CurrentSearchUrl%>"><span>Current search Page
 </span></a> 

  <li><a href="<%#CurrentSearchUrlParam%>"><span>Add param </span>
      </a> 

in the Page_Load

    CurrentSearchUrl = Request.Url.AbsoluteUri;
    CurrentSearchUrlParam = Request.Url+"&discount=1";

param is added but url is not correct my current url is

http://localhost:1067/search/default.aspx?q=test

I want to add one parameter, the desired result should be

http://localhost:1067/search/default.aspx?q=test&discount=1

Thanks in advance

Upvotes: 7

Views: 26953

Answers (4)

John Sharp
John Sharp

Reputation: 782

A small modification to the previous modification... As paramValues is a NameValueCollection you can access them with the this[] parameters.

    var uriBuilder = new UriBuilder(Request.Url.AbsoluteUri);
    var paramValues = HttpUtility.ParseQueryString(uriBuilder.Query);

    paramValues["param1"] = "value1";
    paramValues["param2"] = "value2";
    uriBuilder.Query = paramValues.ToString();

    Link1.HRef=uriBuilder.Uri;

Upvotes: 0

bruno leclerc
bruno leclerc

Reputation: 342

Be careful of already existing parameters. Here is a small modification of Victor' code:

var uriBuilder = new UriBuilder(Request.Url.AbsoluteUri);
var paramValues = HttpUtility.ParseQueryString(uriBuilder.Query);

if(paramValues.Get("param1")!=null) paramValues.Remove("param1");
paramValues.Add("param1", "value1");
paramValues.Add("param2", "value2");
uriBuilder.Query = paramValues.ToString();

Link1.HRef=uriBuilder.Uri;

Upvotes: 11

Victor Mukherjee
Victor Mukherjee

Reputation: 11025

var uriBuilder = new UriBuilder(Request.Url.AbsoluteUri);
var paramValues = HttpUtility.ParseQueryString(uriBuilder.Query);
paramValues.Add("param1", "value1");
paramValues.Add("param2", "value2");
uriBuilder.Query = paramValues.ToString();

Link1.HRef=uriBuilder.Uri;

Upvotes: 25

Habib Rahmoun
Habib Rahmoun

Reputation: 208

There are many way to do that. For example :

Your HTML :

<li class="active">
  <a href="" runat="server" ID="Link1"><span>Current search Page
 </span></a> 

  <li><a href="" runat="server" ID="Link2"><span>Add param </span>
      </a> 

In the Page_Load :

Link1.HRef = HttpContext.Current.Request.Url.ToString();
Link2.HRef = HttpContext.Current.Request.Url.ToString()+"&discount=1";

Upvotes: 2

Related Questions