我知道这个问题已经在一年多前得到了回答,但我想添加我的解决方案,恕我直言,这是最干净的。
我基本上做的是这个(使用Newtonsofts Json.Net)。我为 HtmlHelper 类创建了一个扩展方法,如下所示:
public static class HtmlHelperExtensions
{
public static HtmlString ToJson(this HtmlHelper @this, object value)
{
return new HtmlString(JsonConvert.SerializeObject(value));
}
public static HtmlString ToJson(this HtmlHelper @this, object value, Formatting formatting)
{
return new HtmlString(JsonConvert.SerializeObject(value, formatting));
}
}
这让我可以做到:
$scope.test = @(Html.ToJson(new []
{
new {id='1',name="Hello", desc="World"},
new {id='1',name="Hello", desc="World"},
new {id='1',name="Hello", desc="World"}
}));
结果是:
$scope.test = [{"id":"1","name":"Hello","desc":"World"},{"id":"1","name":"Hello","desc":"World"},{"id":"1","name":"Hello","desc":"World"}];
基本上你的例子会变成这样:
@(Html.ToJson(ViewBag.States.Select(s=>new {id=s["ID"], name=s["Name"]})))
或者
@(Html.ToJson(
from state in ViewBag.States
select new {id=state["ID"], name=state["Name"]}))