我正在将JS本地化资源中存在的本地化键/值对输出到lang.js
,如下所示:
[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 :(得分:0)
看起来你想要返回一个脚本,而不是一个json对象。在这种情况下,我会做两件事之一
答案 1 :(得分: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>