Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a Dictionary to string of url parameters?

Is there a way to convert a Dictionary in code into a url parameter string?

e.g.

// An example list of parameters Dictionary<string, object> parameters ...; foreach (Item in List) {     parameters.Add(Item.Name, Item.Value); }  string url = "http://www.somesite.com?" + parameters.XX.ToString(); 

Inside MVC HtmlHelpers you can generate URLs with the UrlHelper (or Url in controllers) but in Web Forms code-behind the this HtmlHelper is not available.

string url = UrlHelper.GenerateUrl("Default", "Action", "Controller",      new RouteValueDictionary(parameters), htmlHelper.RouteCollection ,      htmlHelper.ViewContext.RequestContext, true); 

How could this be done in C# Web Forms code-behind (in an MVC/Web Forms app) without the MVC helper?

like image 202
lko Avatar asked May 07 '14 13:05

lko


People also ask

How to pass dictionary as Parameter in URL?

You may try this: var parameters = new Dictionary<string, string>(); // You pass this var url = "http://www.somesite.com?"; int i = 0; foreach (var item in parameters) { url += item. Key + "=" + item. Value; url += i !=

What is URL query string and parameters?

URL parameters (known also as “query strings” or “URL query parameters”) are elements inserted in your URLs to help you filter and organize content or track information on your website. To identify a URL parameter, refer to the portion of the URL that comes after a question mark (?).


2 Answers

One approach would be:

var url = string.Format("http://www.yoursite.com?{0}",     HttpUtility.UrlEncode(string.Join("&",         parameters.Select(kvp =>             string.Format("{0}={1}", kvp.Key, kvp.Value))))); 

You could also use string interpolation as introduced in C#6:

var url = $"http://www.yoursite.com?{HttpUtility.UrlEncode(string.Join("&", parameters.Select(kvp => $"{kvp.Key}={kvp.Value}")))}"; 

And you could get rid of the UrlEncode if you don't need it, I just added it for completeness.

like image 196
Mike Perrenoud Avatar answered Sep 18 '22 14:09

Mike Perrenoud


Make a static helper class perhaps:

public static string QueryString(IDictionary<string, object> dict) {     var list = new List<string>();     foreach(var item in dict)     {         list.Add(item.Key + "=" + item.Value);     }     return string.Join("&", list); } 
like image 34
JuhaKangas Avatar answered Sep 16 '22 14:09

JuhaKangas