【发布时间】:2015-01-05 14:43:00
【问题描述】:
我有一个服务器生成的对象,我需要将其转换为 JSON 对象以供 JavaScript 使用。我更喜欢在视图呈现时将这个 JSON 对象直接呈现到 JS 变量中,以防止额外的 HTTP 请求。
这是在我的控制器中:
public virtual JsonResult GetTheThings()
{
return Json(new
{
foo = "hello world",
bar = 3,
}, JsonRequestBehavior.AllowGet);
}
我可以通过http://localhost:32243/MyController/GetTheThings 直接访问它,并在我的浏览器中呈现以下内容。
{"foo":"hello world", "bar":3}。完美!
所以,现在我基本上只是想把这个视图的结果渲染成一个字符串。我该怎么做呢?我在下面的内容不起作用,但希望它能给你这个想法。
这是我的尝试
<script>
var myObj = @Html.RenderPartial(MVC.MyController.GetTheThings());
</script>
请注意,我也在使用 T4 模板。
最后,这就是我想要在视图中呈现的内容。
<script>
var myObj = {"foo":"hello world", "bar":3};
</script>
【问题讨论】:
-
你可以试试
Html.Action,但我不确定这是否可行 -
你试过
var myObj = MVC.MyController.GetTheThings();吗? -
或者
Html.Partial... -
@Shoe 是的,这只会输出
var myObj = T4MVC_System_Web_Mvc_JsonResult;
标签: c# asp.net-mvc json razor t4mvc