将Dictionary转换为url参数字符串? [英] Convert a Dictionary to string of url parameters?

查看:72
本文介绍了将Dictionary转换为url参数字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将代码中的Dictionary转换为url参数字符串?

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

例如

// 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();

在MVC HtmlHelpers内部,您可以使用UrlHelper(或控制器中的Url)生成URL,但是在Web窗体代码中,此HtmlHelper后面不可用.

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);

在没有MVC帮助器的情况下,如何在C#Web窗体代码隐藏(在MVC/Web窗体应用程序中)中完成此操作?

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

推荐答案

一种方法是:

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

您还可以使用C#6中引入的字符串插值:

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}")))}";

如果您不需要它,可以摆脱 UrlEncode ,我只是为了完整性而添加了它.

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

这篇关于将Dictionary转换为url参数字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆