gpt4 book ai didi

javascript - 通过 MVC 和 RAZOR 编写 JSON

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:16:45 31 4
gpt4 key购买 nike

我有一个 ASP.NET MVC 4 应用程序。这个应用程序有一个 View ,在页脚中有一个 javascript block 。我正在使用 RAZOR View 引擎。我想弄清楚如何将我的结果集转换为 JSON 数组。目前,我正在执行以下操作:

<script type="text/javascript">
@for (int i=0; i<ViewBag.States.Count; i++) {
<text>
{ id: @Html.Raw(ViewBag.States[i]["ID"], name: \"" + ViewBag.States[i]["Name"] + "\"}")
</text>
if (i < (ViewBag.States.Count - 1)) {
<text>,</text>
}
}
</script>

这种方法在句法上似乎很草率。但是,我不确定该怎么做。有谁知道我该如何清理它?使用这种方法,我什至不知道如何用引号将“ID”值引起来。

最佳答案

我知道这个问题已经在一年多以前得到了回答,但我想添加我的解决方案,恕我直言,这是最干净的。

我基本上是这样做的(使用 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"]}))

关于javascript - 通过 MVC 和 RAZOR 编写 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15281647/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com