我正在开发一个 ASP.NET MVC3 应用程序,我想从视图调用控制器并将该信息存储为字典。
控制器代码:
public Dictionary<string,int> foo()
{
Dictionary<string,int> bar = new Dictionary<string,int>();
bar.Add("test",100);
return bar;
}
查看代码:
@{ Dictionary<string,int> foobar = Html.Action("foo"); }
...
<div>@foobar["test"]</div>
如果我使用var foobar = Html.Action("foo");
,我可以让视图工作,但它只是说 foobar 是 type System.Web.Mvc.MvcHtmlString
,所以我不能用它做太多。
是否有任何我缺少的内置功能,或者我应该为此使用类似 JSON 结果的东西?
编辑:附加信息
还应该注意的是,在 VS2010 调试器中,它将 foobar 正确识别为{System.Collections.Generic.Dictionary'2[System.String,System.Int32]}
,所以问题是 foobar 没有正确解析。抛出的错误是:
Compiler Error Message: CS0021: Cannot apply indexing with []
to an expression of type 'System.Web.Mvc.MvcHtmlString'
编辑 2
这些是将结果转换为字典时出现的错误:
Url.Action("foo").ToDictionary<string,int>();
出于明显的原因返回CS1501: No overload for method 'ToDictionary' takes 0 arguments
,但 VS2010 调试器识别出结果是字典:
但是当我添加参数 ( Url.Action("foo").ToDictionary<string,int>(x=>x);
) 时,它会停止识别它是一个字典,尽管我不确定这些参数是否正确(它基于我在此处找到的内容。