2

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>
DLeh
  • 23,806
  • 16
  • 84
  • 128
Chris Barr
  • 29,851
  • 23
  • 95
  • 135

5 Answers5

2

Since you only want the object to be rendered when the view is rendered (and not from an AJAX call), your best bet is probably to make it part of your model. Create a string property and save the JSON as a string, then use JSON.parse in your View to convert it to an object.

Example:

<script>
    var myObj = JSON.parse("@Html.Raw(Model.JsonString)");
</script>

Much cleaner that way, and there really isn't any good reason to have your controller doing this since you aren't requesting the object via AJAX.

Douglas Barbin
  • 3,595
  • 2
  • 14
  • 34
1

You could create an HtmlHelper extension like so and instead of using a JsonResult, use a strongly-typed view (assuming using JSON.Net):

public static class HtmlHelperEx
{
    public static string ToJson(this HtmlHelper html, object obj)
    {
        return JsonConvert.SerializeObject(obj);
    }
}

Controller Action:

public ActionResult Index() 
{
   return View(new ModelToSerialize());
}

Then use it in your view like:

@model ModelToSerialize

<script type="text/javascript">
    var myObj = @Html.ToJson(Model)
</script>
Mark Olsen
  • 939
  • 7
  • 10
  • Perfect solution. And being able so use the model in the HTML before returning is as JSON. Just needed to add @Html.Raw(@Html.ToJson(Model)); to avoid htmlencoding of the json. – Kasper Jensen Aug 26 '16 at 08:25
0

You would theoritically be able to do it like this:

<script>
  var myObj = json.parse('@Html.RenderPartial(MVC.MyController.GetTheThings());');
</script>

Although, GetTheThings() will not actually fire here, it's just a T4MVC placeholder. You should probably store your value into a view model, and get it into javascript like below. If you want to make a separate call to a controller to get this value, it will need to be an ajax call.

public class MyController
{ 
    public ActionResult MyView(){
        var vm = new MyViewModel();
        vm.MyObjectAsJsonString = GetMyJsonString();
        return View(vm);
    }
    public string GetMyJsonString(){
         return ""; //get your json 
    }
}

public class MyViewModel
{
    public string MyObjectAsJsonString{ get; set; }
}

@model MyViewModel
<script>
  var myObj = json.parse('@Model.MyObjectAsJsonString');
</script>

To do it via ajax:

<script>
    $.ajax({
        url: '@Url.Action(MVC.MyController.GetTheThings())',
        type: 'get',
    }).done(function (result){
        var myObj = result;
    });
</script>
DLeh
  • 23,806
  • 16
  • 84
  • 128
  • I'm not having an issue parsing the json object, I'm having an issue getting MVC to render out the view here. Also, as I stated above I want to render it in the view instead of another AJAX call to avoid additional HTTP requests. – Chris Barr Jan 05 '15 at 14:53
  • you can do it without an ajax call, but you will need to store it in the view model. The View cannot call the controller directly, the controller is already done being used when the view is being rendered. – DLeh Jan 05 '15 at 14:54
  • see my edit for an example of how to parse from the json in a view model. – DLeh Jan 05 '15 at 14:56
0
<script>
  var myObj = '@Html.RenderPartial("Getthethings","controller name");'
</script>
dotnetstep
  • 17,065
  • 5
  • 54
  • 72
0

Use the @Html.Raw(...) wrapper.

In my own project, I do refer to the existing model coming down in from the controller itself, but there's no reason you can't get the same effect as a partial...it's just not really the core purpose of using async calls...which you should be using instead of relying on the html rendering engine to do your 'dirty' work.

beauXjames
  • 8,222
  • 3
  • 49
  • 66