对不起,这个假问题,但我找不到一个简单而干净的方法来做这样简单的事情。我有一个MVC控制器,它应该返回一个JSON对象以供某些JavaScript使用;如果我将它的返回类型设置为JsonResult并返回Json(objecttoserialize),我可以通过Firebug看到JSON代码被返回并正确解释。无论如何,我必须使用手动编码的JSON字符串,因为:
例如,字典中的条目,如键的“宽度”和值的" 20“,必须序列化为{ width:"20”},也就是说,就好像.NET对象有一个值为20的属性宽度,而它只是有一个字典,其中包含由JS对象中的对象属性表示的这些属性/值对的可变数目。这就是为什么组件有自己的JSON序列化方法的原因。因此,我应该返回它生成的JSON。
当Json方法序列化.NET输入对象时,我搜索了一下,我发现我更愿意使用ContentResult。因此,我尝试返回一个带有ContentResult序列化字符串和ContentType =“application/ JSON”的Content=the;无论如何,JS客户机似乎无法理解这是一个JSON对象,并且失败了。如果我返回一个JsonResult,它就会像预期的那样工作,但是它的字典成员所表示的属性当然会丢失。我原以为JsonResult相当于上面的ContentResult,但情况似乎并非如此。JS代码类似于:
request: function (nodeId, level, onComplete) {
$.ajax({
url: "/Node/Get", type: "POST", dataType: "json",
data: { id: nodeId, level: level, depth: 3 },
success: function (data) {
var ans = data;
onComplete.onComplete(nodeId, ans);
}
});如果我在Firebug中的脚本中放置了一个断点,当我返回JsonResult时,成功函数就会被击中;当我返回ContentResult时,它永远不会被击中,并且页面仍然停留在加载所请求的对象上。(这个JS指的是SpaceTree of www.thejit.org)。有人能给点提示吗?
发布于 2012-07-04 06:52:28
我设法让它使用了某种技巧,但我想知道是否有更好的解决方案,而且至少我确实需要使用JsonResult (或派生类,比如这个技巧)来使JS正常工作。我从JsonResult派生了一个类,并更改了ExecuteResult方法,以便它只通过接收到的JSON字符串:
public sealed class PassthroughJsonResult : JsonResult
{
public string Json { get; set; }
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
throw new ArgumentNullException("context");
HttpResponseBase response = context.HttpContext.Response;
if (!String.IsNullOrEmpty(ContentType))
response.ContentType = ContentType;
else
response.ContentType = "application/json";
if (ContentEncoding != null)
response.ContentEncoding = ContentEncoding;
if (Json != null) response.Write(Json);
}
}https://stackoverflow.com/questions/11315558
复制相似问题