0

I have a C# class like this

public class Person
{
  string firstname {get; set;}
  string lastname {get; set;}
  string onRenderFunction {get; set;}
}

Then I setup the class like this:

var superman = new Person
{ 
    firstname = "Clark",
    lastname = "Kent",
    onRenderFunction = "renderPersonComplete"
}

What I want is the "onRenderFunction" to be serialized to a method - not a string. Like this;

{ 
  "firstname": "Clark",
  "lastname": "Kent",
  "onRenderFunction": renderPersonComplete
}

So when the serialized object is returned via an Ajax call and given to a plugin which has the ability to call a function "onRenderFunction", the plugin would see the function is set and call a function setup like this:

var renderPersonComplete = function() {
   alert('do something on render complete');
};

How would I setup JSON.NET to serialize the Person class to do this?

6
  • What do you mean by "onRenderFunction" to be serialized to a method"? Do you want to assign a JavaScript function to a string property in C#? Commented Jan 3, 2015 at 16:52
  • Added more detail to the function. I am passing the serialized object as a Javascript object via an Ajax call to a jQuery plugin. The plugin sees if the onRenderFunction property on the javascript object is a function and if so calls it. Commented Jan 3, 2015 at 16:56
  • Why not just add the function to the JS object after you get the data from ajax? Commented Jan 3, 2015 at 17:06
  • The object to be serialized is setup server side and the callback changes with business logic. I need the ability to setup the entire object given to the plugin. Commented Jan 3, 2015 at 17:13
  • The way to do it is to use javascript eval. It an be done this way eval(yourjsonobject.onRenderFunction) Commented Jan 3, 2015 at 17:15

1 Answer 1

1

You have to do some additional processing to assign the function to the property because JSON by definition is just key-value pairs of primitives, it does not know functions.

So initially your data from ajax will look like:

var data = { 
  "firstname": "Clark",
  "lastname": "Kent",
  "onRenderFunction": "renderPersonComplete"
}

Let's say you have a function called renderPersonComplete in window's scope:

window.renderPersonComplete = function() {
   alert('do something on render complete');
};

Now you have to modify your data to assign the function:

data.onRenderFunction = window[data.onRenderFunction] // This assigns the function to onRenderFunction  property.

The name of the function is decided in the server side based on your logic.

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.