Smartelf
Smartelf

Reputation: 879

Serializing JS Functions into JSON for a JsonResult MVC

I am writing a backend for SlickGrid. I have an AJAX call that loads the column definitions from my MVC Controller. The controller looks like this:

Public ActionResult GetColumns(...){
    List<object> columns;
    foreach(var col in MyColumns){
        columns.Add(new { id = col.id, name = col.name, width = col.width});
    }
    return Json(new { columns = columns });
}

One of the column attributes that slickgrid accepts is formatter, which takes a js function name.

Unfortunately, MVC puts that name in double quotes. I need to figure out if there is a way to serialize just that one field without quotes.

eg (this is what I want)

[{"id":1,"Name":"FirstName","width":50,"formatter":NameFormater},...]

vs (ths is what I am getting now)

[{"id":1,"Name":"FirstName","width":50,"formatter":"NameFormater"},...]

I know this isn't proper JSON Format to pass JS Code in it(Proper JS Format though). But I have a valid use case here and am trying not to add too much complexity.

Upvotes: 0

Views: 88

Answers (1)

rleffler
rleffler

Reputation: 470

You could wrap the word NameFormater with special characters such as

[{"id":1,"Name":"FirstName","width":50,"formatter":"#NameFormater#"},...]

and when you get your results back, if you are using javascript

 function(result){

    result = result .replace(/"#/g, "");
    result = result .replace(/#"/g, "");


// result now =  [{"id":1,"Name":"FirstName","width":50,"formatter":NameFormater},...]
//    ...Pass result to SlickGrid

    }

Upvotes: 1

Related Questions