Search code examples
c#asp.net-mvcdictionarywebforms

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?


Solution

  • One approach would be:

    var url = string.Format("https://example.org?{0}",
        string.Join("&",
            parameters.Select(kvp =>
                string.Format(
                    "{0}={1}",
                    kvp.Key,
                    HttpUtility.UrlEncode(kvp.Value.ToString())))));
    

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

    var url = $"https://example.org?{string.Join("&", parameters.Select(kvp => $"{kvp.Key}={HttpUtility.UrlEncode(kvp.Value.ToString())}"))}";
    

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