I have a server-generated object that I need to convert to a JSON object for JavaScript to consume. I prefer to render this JSON object directly into a JS variable when the view renders to prevent an additional HTTP request.
This is in my controller:
public virtual JsonResult GetTheThings()
{
return Json(new
{
foo = "hello world",
bar = 3,
}, JsonRequestBehavior.AllowGet);
}
I can access this directly at http://localhost:32243/MyController/GetTheThings
and I get the following rendered in my browser.
{"foo":"hello world", "bar":3}
. Perfect!
So, now I basically just want to render the result of this view into a string. How do I do this? What I have below does not work, but hopefully it give you the idea.
This is my attempt
<script>
var myObj = @Html.RenderPartial(MVC.MyController.GetTheThings());
</script>
Note that I am also using T4 Templates.
In the end, this is what I want to be rendered in the view.
<script>
var myObj = {"foo":"hello world", "bar":3};
</script>