user49126
user49126

Reputation: 1863

Returning JSON from action method

I have this action methid. It will return some JSON.

public JsonResult Get()
{
        ...

        return new JsonResult { Data = data }, JsonRequestBehavior = JsonRequestBehavior.AllowGet };  
}

Then I have in my view a script tag pointing to the Get action method.

 <script type="text/javascript" src="@Url.Content("~/resource/get")"></script>

The problem is I can't access the JSON data in JS code. It seems like the JSON needs to be executed somehow. Any suggestion ?

Upvotes: 1

Views: 1280

Answers (3)

Andrew Lewis
Andrew Lewis

Reputation: 5256

If you want it to be dumped into your HTML at the time the page is built on the server, you can add it to your view model, then render it directly on the page. Here's a pseudo-code example:

<script type="javascript">
     var obj= JSON.parse('@Model.PropertyContainingJson');
</script>

Upvotes: 1

Kyle Trauberman
Kyle Trauberman

Reputation: 25684

If you want the JSON available ASAP, without an extra request, include it in the initial page load:

<script type="text/javascript">
    var myJson = @Html.Action("Get");
</script>

Now you can just access the myJson variable in your script to access your data.

Upvotes: 1

Kenneth
Kenneth

Reputation: 28737

You can just call the action in jQuery and then process the Json directly:

$.ajax({
  dataType: "json",
  url: "/resource/get",
  success: function(data){
      var obj = JSON.parse(data);
  }
});

Or a shorter version:

$.getJSON('/resource/get', function(data) { 
    var obj = data;
});

Upvotes: 2

Related Questions