views:

87

answers:

3

Hello,

I am using Flexigrid in my project to add a button on the grid toolbar I can use code like this:

...    
"buttons":[
    {"name":"Modifica","bclass":"edit","onpress":"doCommand"},
    {"name":"Elimina","bclass":"delete","onpress":"doCommand"}
],
...

Anyway the "onpress" attribute shall contain a reference to a js callback and so this field shall not be enclosed within quotation marks.

I am using the class JavaScriptSerializer (in the System.Web.Script.Serialization namespace) to do the serialization.

How I have to declare the variable to make JavaScriptSerializer serialize like this?

...    
"buttons":[
    {"name":"Modifica","bclass":"edit","onpress":doCommand},
    {"name":"Elimina","bclass":"delete","onpress":doCommand}
],
...

Thanks for helping!

A: 

JavaScriptSerializer is meant for serializing to JSON, and JSON can not represent functions; it also can't refer to previously defined variables. So I don't believe this is possible.

Matthew Flaschen
Well...you're right. But I have used to build a fluent interface for the grid declaration. There is no way to do this?
Lorenzo
@Lorenzon, there may be a way to get the JavaScript output you want, but not with JavaScriptSerializer alone.
Matthew Flaschen
A: 

To the best of my knowledge, there is not a native way to do this with the .NET serializer, but you could execute the following code on the client-side to turn the onpress JSON string into a callback...

var buttons = []; // Your JSON array
for(var i = 0; i < buttons.length; i++) {
  var b = buttons[i];
  b.onpress = window[b.onpress];
}
Josh Stodola
Is there a need for an eval there ? window[oldOnPress]() should work ?
letronje
You don't need the outer function either. Just `b.onpress = window[b.onpress];`
Matthew Flaschen
Good point, I have edited the answer accordingly
Josh Stodola
@Josh: Good! Anyway I did not take this approach because I wanted everything packed inside my HTML helper extension. So I have changed the code in the extension to do something very similar to your suggestion. Thanks!
Lorenzo
A: 

You can store the function name as a string

...    
"buttons":[
    {"name":"Modifica","bclass":"edit","onpress":"doCommand"},
    {"name":"Elimina","bclass":"delete","onpress":"doCommand"}
],
...
letronje
This is not correct. If you read my question, they're already stored as strings and this does not work because the plugin wants reference to function not function name... ;)
Lorenzo