使用以下代码:
var stocks = new Dictionary<string, string>() {{"MSFT", "Microsoft Corporation"}, {"AAPL", "Apple, Inc."}};
<a href="@Url.Action("Test", new {stocks})">Test Item</a>创建的URL为:
http://localhost:58930/d/m/5b1ab3a0-4bb3-467a-93fe-08eb16e2bb8d/Center/Test?stocks=System.Collections.Generic.Dictionary%602%5BSystem.String%2CSystem.String%5D它显示类型而不是数据。为什么会这样呢?如何传递数据?
发布于 2012-02-02 00:05:18
这是因为Dictionary<T, U>不会覆盖ToString()。以这种方式创建的匿名对象,var stocks = new { MSFT = "Microsoft Corporation", AAPL = "Apple, Inc." };,这样做。当调用ToString()时,匿名对象会生成{ MSFT =微软公司,AAPL =苹果公司}作为其输出,操作将对其进行解析以创建参数。我相信您也应该能够使用像这样创建的System.Web.Routing.RouteValueDictionary,RouteValueDictionary stocks = new RouteValueDictionary { { "MSFT ", "Microsoft Corporation" }, { "AAPL", "Apple, Inc." } };。
发布于 2012-02-02 20:41:58
UrlHelper.Action接受在内部转换为RouteValueDictionary的匿名对象
Url.Action("Test", new { "MSFT" = "Microsoft Corporation", "APPL" = "Apple, Inc." })或者直接使用RouteValueDictionary
Url.Action("Test", new RouteValueDictionary() {{}})并且它将字典关键字与动作参数进行匹配。如果它们匹配,则将该值添加到查询字符串(或路由路径,具体取决于Url路由规则)。
因此,如果您的操作没有名为MSFT或APPL的参数,则路由将不起作用。您需要使用serialize the dictionary (或以字符串形式传递数据的任何其他方式),并将其作为编码字符串(使用HttpServerUtility.UrlEncode)传递给UrlHelper
Url.Action("Test", new { "stocks", serializedDictionary });然后,在该操作中,您必须从序列化的字典中再次提取数据。
https://stackoverflow.com/questions/9098848
复制相似问题