2

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!

4 Answers 4

4

How about this trick ?

var param = new Dictionary<string,string>();

param["onpress"] = "%doCommand%";

return new JavaScriptSerializer().Serialize( param ).Replace( "\"%", "" ).Replace( "%\"", "" );
Sign up to request clarification or add additional context in comments.

Comments

0

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];
}

3 Comments

Is there a need for an eval there ? window[oldOnPress]() should work ?
You don't need the outer function either. Just b.onpress = window[b.onpress];
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!
0

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.

2 Comments

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

You can store the function name as a string

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

1 Comment

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... ;)

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.