开发者

JavaScriptSerializer to serialize a javascript function name

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":"Modific开发者_开发问答a","bclass":"edit","onpress":doCommand},
    {"name":"Elimina","bclass":"delete","onpress":doCommand}
],
...

Thanks for helping!


How about this trick ?

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

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

return new JavaScriptSerializer().Serialize( param ).Replace( "\"%", "" ).Replace( "%\"", "" );


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


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.


You can store the function name as a string

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜