views:

657

answers:

1

Hi,

I've created a linked list class in my JavaScript code and then translated that code into C#.

Right now I have a JavaScript function that calls a Web Service in order to get an array of names, the JavaScript onComplete function then takes that array and makes it into a linked list.

Is there any way I can create the linked list in the Web Service and pass it back to be used by the JavaScript code or can linked lists not transfer properly?

Edit: Let me rephrase my question to something that makes a little more sense. If you have a custom made object created by a class say.... class User, and that class has a variable called user name. If you pass a User object: objUser, back from C# to JavaScript, how does the JavaScript know it can access objUser.userName? What about possible methods it can invoke on this user object?

+1  A: 

I had a similar question when I was creating my ASP.NET MVC application. Basically the answer is that JavaScript does not have the same concept of Types as in C#.

Let's say that you've decided to use JSON to pass data between your client and server in your application. The choice of JSON, XML, YAML or other format is not important.

Server Side

On your server side, in your C# code, you can do something like this (assuming you are using a JSON library of some sort):

var myLinkedList = JsonConvert.DeserializeObject<LinkedList>(json);

Now you've got a myLinkedList variable of Type LinkedList. myLinkedList now behaves like all LinkedList instances.

Client Side

However on the client site, in your JavaScript code, you probably do something like this:

function LinkedList(){
    //Constructor for your LinkedList
};

LinkedList.prototype = {
    //Various functions to operate on your linked list
};

You need to write something like this to deserialize the data that returns from the server:

var linkedList = JSON.parse(jsonString);

Note that there is NO WAY to indicate that you want this deserialized data to go into the LinkedList "class" that you've defined earlier. JavaScript does not understand that LinkedList is a "class" that you've added functionality to using prototype.

What you get back is a JavaScript object.

One way to get around this is to do something like this:

var linkedList = new LinkedList();
var deserializedObject = JSON.parse(jsonString);

linkedList.Items = deserializedObject.Items;

Basically, you'd have to copy over all the state from your deserialized object into your linkedList variable.

Praveen Angyan
JSON stands for "Javascript Object Notation" and is a data format for exchanging objects between JavaScript and your back end code and vice versa.Use a library like JSON.NET in your C# code and a parsing library like that found on www.json.org to work with JSON in your code.
Praveen Angyan