0

很抱歉这个虚拟问题,但我找不到一种简单而干净的方法来做这么简单的事情。我有一个 MVC 控制器,它应该返回一个 JSON 对象以供某些 JavaScript 使用;如果我将其返回类型设置为 JsonResult 并返回 Json(objecttoserialize) 我可以通过 Firebug 看到 JSON 代码被正确返回和解释。无论如何,我必须使用手动编码的 JSON 字符串,因为:

  • 序列化我要返回的对象的组件托管在外部库中,我不应该触摸它。
  • 该组件自行序列化,因为它有一个 Dictionary 成员,表示相应 JS 对象的属性 NAME 和 VALUE。

例如,字典中的条目(如键的“宽度”和值的“20”)必须序列化为 { width: "20" },即好像 .NET 对象具有值为 20 的属性 Width,而它只是有一个字典,其中包含可变数量的此类属性/值对,由 JS 对象中的对象属性表示。这就是组件有自己的 JSON 序列化方法的原因。因此,我应该只返回它生成的 JSON。

由于 Json 方法序列化了一个 .NET 输入对象,我四处搜索发现我宁愿使用 ContentResult。因此,我尝试通过返回 ContentResult 与 Content=the 序列化字符串和 ContentType = "application/json"; 无论如何,JS 客户端似乎无法理解这是一个 JSON 对象并且失败了。相反,如果我返回一个 JsonResult 它会按预期工作,但它的 Dictionary 成员表示的属性当然会丢失。我期待 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 指的是 www.thejit.org 的 SpaceTree)。谁能给个提示?

4

1 回答 1

0

我设法用一种技巧让它工作,但我想知道是否有更好的解决方案,无论如何我真的需要使用 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);
  }
}
于 2012-07-04T06:52:28.580 回答