我有一个服务器生成的对象,需要将其转换为 JSON 对象以供 JavaScript 使用。我更喜欢在 View 渲染时将此 JSON 对象直接渲染到 JS 变量中,以防止额外的 HTTP 请求。
这是在我的 Controller 中:
public virtual JsonResult GetTheThings()
{
return Json(new
{
foo = "hello world",
bar = 3,
}, JsonRequestBehavior.AllowGet);
}
我可以直接在 http://localhost:32243/MyController/GetTheThings
访问它,并在浏览器中呈现以下内容。
{"foo":"hello world", "bar":3}
。完美!
所以,现在我基本上只想将此 View 的结果呈现为字符串。我该怎么做呢?我下面的内容不起作用,但希望它能给您带来想法。
这是我的尝试
<script>
var myObj = @Html.RenderPartial(MVC.MyController.GetTheThings());
</script>
请注意,我也在使用 T4 模板。
最后,这就是我想要在 View 中呈现的内容。
<script>
var myObj = {"foo":"hello world", "bar":3};
</script>
最佳答案
由于您只希望在呈现 View 时呈现对象(而不是通过 AJAX 调用),因此最好的选择可能是使其成为模型的一部分。创建一个字符串属性并将 JSON 保存为字符串,然后在 View 中使用 JSON.parse
将其转换为对象。
示例:
<script>
var myObj = JSON.parse("@Html.Raw(Model.JsonString)");
</script>
这样就干净多了,而且确实没有任何充分的理由让你的 Controller 这样做,因为你没有通过 AJAX 请求对象。
关于c# - 将 JsonResult 渲染为 Razor 中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27781815/