Reputation: 60674
I have a JSON-like data structure (which I don't want to change) that is currently generated by an .aspx
file spitting out javascript. It looks like .NET ate jQuery for lunch, and then vomited...
I'd like to rewrite the entire thing to an MVC controller action that returns a JsonResult
, basically by building up an anonymous object and pass it to return Json(data)
.
However, I can't figure out how to construct the C# object when some of the properties on the JSON object I want to build are actually JavaScript functions. How do I do that?
Example:
I want to create the following JSON-like object:
{
id: 55,
name: 'john smith',
age: 32,
dostuff: aPredefinedFunctionHandle,
isOlderThan: function(other) { return age > other.age }
}
You see that I want to be able to specify both function handles to JavaScript functions that I have defined elsewhere (in .js
files, usually) and that I want to define new inline functions.
I know how to build part of that object in C#:
var data = new { id = 55, name = "john smith", age = 32 };
return Json(data);
Is there any good way to do also the rest of it?
Upvotes: 4
Views: 1283
Reputation: 2121
JSON excludes functions. It sounds like you want to encapsulate your data into a class. How about something like the following:
function Person(data) {
this.id = data.id;
this.name = data.name;
this.age = data.age;
this.isOlderThan = function(other) { return this.age > other.age };
}
Upvotes: 0
Reputation: 32768
There is no built-in type in .NET that maps to javascript function. So you may have to create a custom type that represents a function and you have to do the serialization yourself.
Something like this..
public class JsFunction
{
public string FunctionString{get; set;}
}
new
{
id = 55,
name = 'john smith',
age = 32,
dostuff = new JsFunction{ FunctionString = "aPredefinedFunctionHandle" },
isOlderThan = new JsFunction{ FunctionString = "function(other) { return age >
other.age" }
}
On serialization you may have to check the type of the value and write the FunctionString
directly into the response without double-quotes.
Upvotes: 2
Reputation: 19037
JSON explicitly excludes functions because it isn't meant to be a JavaScript-only data structure (despite the JS in the name). So we should not include function name in JSON
Upvotes: 0