2011-12-23 56 views
0

我输出存在于JS本地化资源定位键/值对成lang.js这样的:输出变量名JSON结果之前

[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); 
    } 

/js/lang.js的内容是(我有一个正常<script>标签的文件):

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

有没有什么办法让他们成为:

var LANG = {"Test":"test","_Lang":"en"} 
+0

考虑一些建议包含在[这篇文章关于JSONP在MVC3](http://stackoverflow.com/a/4797071/416518),这有趣的足够[Darin Dimitrov](http://stackoverflow.com/users/29407 /达林-dimitro v)谁在下面提供了答案。 :) – lsuarez 2011-12-23 20:53:45

回答

0

您可以使用JSONP。编写自定义操作结果:

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

,然后在你的控制器行动回报吧:

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

最后定义回调包括脚本之前捕捉到JSON:

<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> 
+0

完美。谢谢! – Normandy 2011-12-23 21:00:56

0

它看起来像你想要返回一个脚本,而不是一个JSON对象。在这种情况下,我会做的两件事情

一个
  1. 返回一个封装脚本,而不是JSON(不知道如果存在的话)
  2. 返回JSON,然后是JSON设置在一个局部变量的作用结果客户端(典型的阿贾克斯调用)