0

I need to generate a JSON object from server containing data to be cached on client. I placed the following:

<script src='Path to js file on server" />

At the server, I generated my json data and placed them inside the JS file.

I can see the generated JSON object on the client-side something as:

var jsonData = [{}, {}];

However, when I try to access jsonData object, it says, undefined!

Is there another way to generate valid javascript from server side?

Thanks


This is the server-side code:

var items = List<myObj>();

string json = JsonConvert.SerializeObject(items, Formatting.Indented);

StringBuilder sb = new StringBuilder();
sb.AppendLine();
sb.AppendFormat("    var jsonData = {0};", json);

var fileName = Request.PhysicalApplicationPath + "Scripts/Data.js";
System.IO.File.WriteAllText(fileName, sb.ToString());

As for client side:

<script src='@Url.Content("~/Scripts/Data.js")' type="text/javascript"></script>

I tried to use this code on the client:

alert(jsonData[0].Id);

It says, jsonData is undefined!

Regards

5
  • Post a sample json data and the code that tries to use it Commented Mar 16, 2012 at 10:37
  • Are you trying post back json or Javascript code? These are two things that are built differently. Commented Mar 16, 2012 at 10:39
  • @ianaldo21 json is javascript object notation. Commented Mar 16, 2012 at 12:30
  • @jrummell JSON is really different thing. In current case this doesn't matter, cause JSON is valid javascript object literal. But not the other way around. Commented Mar 16, 2012 at 14:03
  • @jrummell Yep it's javascript object notation. I didn't say they are two different things, they are built (put together) differently. Commented Mar 16, 2012 at 14:52

1 Answer 1

1

ASP part is ok, the problem seemed to lie in javascript variable scoping plane. Possible problems:

  • You just don't include that js file.
  • You're trying to access variable before it is initialized;
  • Variable isn't visible in place, you're trying to access it.
  • You're not exact in your question and accessing not jsonData, but something like jsonData[0].property

etc.

UPD: Ok, first two options are excluded. Where are you trying to access this variable? Please, show us a portion of code.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.