0

I'm outputting the localization key/value pairs present in the JS localization resource into lang.js like this:

    [Route("js/lang.js")]
    public ActionResult Lang()
    {
        ResourceManager manager = new ResourceManager("Normandy.App_GlobalResources.JsLocalization", System.Reflection.Assembly.GetExecutingAssembly());
        ResourceSet resources = manager.GetResourceSet(CultureInfo.CurrentCulture, true, true);

        Dictionary<string, string> result = new Dictionary<string, string>();

        IDictionaryEnumerator enumerator = resources.GetEnumerator();

        while (enumerator.MoveNext())
            result.Add((string)enumerator.Key, (string)enumerator.Value);

        return Json(result);
    }

The contents of /js/lang.js are (I include the file with a normal <script> tag):

{"Test":"test","_Lang":"en"}

Is there any way to make them be:

var LANG = {"Test":"test","_Lang":"en"}
ziesemer
  • 27,712
  • 8
  • 86
  • 94
Normandy
  • 25
  • 2
  • Consider some of the advice contained in [this post about JSONP in MVC3](http://stackoverflow.com/a/4797071/416518), which is interestingly enough constructed by [Darin Dimitrov](http://stackoverflow.com/users/29407/darin-dimitrov) who has provided an answer below. :) – lsuarez Dec 23 '11 at 20:53

2 Answers2

0

It looks like you want to return a script, instead of a json object. in that case I would do one of 2 things

  1. return an action result that encapsulates a script rather than json (not sure if one exists)
  2. return json and then set that json to a local variable on the client (typical ajax call)
Jason Meckley
  • 7,589
  • 1
  • 24
  • 45
0

You could use JSONP. Write a custom action result:

public class JsonpResult: ActionResult
{
    public readonly object _model;
    public readonly string _callback;

    public JsonpResult(object model, string callback)
    {
        _model = model;
        _callback = callback;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        var js = new JavaScriptSerializer();
        var jsonp = string.Format(
            "{0}({1})", 
            _callback, 
            js.Serialize(_model)
        );
        var response = context.HttpContext.Response;
        response.ContentType = "application/json";
        response.Write(jsonp);
    }
}

and then in your controller action return it:

[Route("js/lang.js")]
public ActionResult Lang()
{
    ...
    return new JsonpResult(result, "cb");
}

and finally define the callback to capture the json before including the script:

<script type="text/javascript">
function cb(json) {
    // the json argument will represent the JSON data
    // {"Test":"test","_Lang":"en"}
    // so here you could assign it to a global variable
    // or do something else with it
}
</script>
<script type="text/javascript" src="js/lang.js"></script>
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928