jQuery的JSON后从ASP.NET MVC返回null时失败 [英] jQuery post JSON fails when returning null from ASP.NET MVC

查看:226
本文介绍了jQuery的JSON后从ASP.NET MVC返回null时失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 ASP.NET MVC 张贴JSON从jQuery的,并得到一些JSON回来了,用这个小库函数:

I use ASP.NET MVC to post JSON from jQuery, and get some JSON back, using this little library function:

(function($) {
    $.postJson = function(url, data) {
        return $.ajax({
            url: url,

            data: JSON.stringify(data),
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json; charset=utf-8'
        });
    };
})(jQuery);

所以,很明显,我会打电话给此类似:

So obviously I'll call this like:

$('#button').click(function() {
    $.postJson('/controller/action', { Prop1: 'hi', Prop2: 'bye' })
    .done(function(r) { alert('It worked.'); })
    .fail(function(x) { alert('Fail! ' + x.status); });
});

ASP.NET MVC 3与ASP.NET MVC 4支持的提交方面的事情(你需要扩展ASP.NET MVC来处理JSON提交之前),但我快到问题上的回报。在控制器我经常返回空值从根本上说成功,没有别的话可说,这样的:

ASP.NET MVC 3 and ASP.NET MVC 4 support the submit side of things (before that you needed to extend ASP.NET MVC to handle submitting JSON), but the problem I'm running into is on the return. On the Controller I often return null to basically say "Success, nothing else to say," like:

[HttpPost]
public JsonResult DoSomething(string Prop1, string Prop2)
{
    if (doSomething(Prop1, Prop2)
        return Json(null); // Success

    return Json(new { Message = "It didn't work for the following reasons" });
}

我经常使用这种模式,它工作得很好 - 我的成功/完成回调被调用,一切都很好。但最近我升级的ASP.NET MVC和jQuery,以及它停止工作 - 而不是我的失败回调获取调用每当我返回JSON(空); 。此外,我已经考察得到返回的响应和状态code其实是在200,因此服务器不会失败 - jQuery的只是称这是

I use this pattern frequently and it works fine - my success/done callback gets called and all is well. But recently I upgraded ASP.NET MVC and jQuery, and it's stopped working - instead my fail callback is getting called whenever I return Json(null);. Furthermore, I've inspected the response and the statusCode getting returned is in fact 200, so the server isn't failing - jQuery's just saying it is.

推荐答案

该问题通过升级从jQuery的1.8至1.9造成的。在jQuery的1.7和1.8,这在MVC中:

The problem was caused by upgrading from jQuery 1.8 to 1.9. In jQuery 1.7 and 1.8, this in MVC:

return Json(null);

被接纳为有效的JSON和PTED为空间$ P $。从技术上讲,这发出了一个空字符串返回给客户端的HTTP 200,并且这是够好了jQuery和LT; 1.9

was accepted as valid JSON and interpreted as null. Technically, this sends a blank string back to the client with HTTP 200, and that's good enough for jQuery <1.9.

但是,现在(我们使用jQuery 1.9.1),它试图解析空字符串作为JSON,jQuery的JSON解析器抛出的空字符串的异常,并触发,在一个结尾的code链失败()回调来代替。

But now (we're using jQuery 1.9.1), it attempts to parse the empty string as JSON, jQuery's JSON parser throws an exception on empty string, and that triggers a code chain that ends in a fail() callback instead.

一个解决方法是,而不是从服务器传递这种背面上的成功,没有其他资料:

A workaround is to instead pass this back from the server on success with no other information:

return Json(new{});

这是通过不屑一顾,jQuery的JSON解析器,一切都很好。这也适用:

That passes muster with jQuery's JSON parser and all is well. This also works:

return Json(true);



穆萨指出低于MVC这种行为似乎打破。该<一href="http://stackoverflow.com/questions/7109967/using-json-net-as-default-json-serializer-in-asp-net-mvc-3-is-it-possible/7150912#7150912">separate堆栈溢出答案的使用JSON.NET为默认的JSON序列在ASP.NET MVC 3 - ?是否有可能的介绍了如何获得MVC到返回null JSON(空) - 基本上,使用Json.NET而不是ASP.NET MVC的内置JSON序列。这是解决方案,我最终结束了使用。

Musa notes below this behavior by MVC seems broken. This separate Stack Overflow answer to Using JSON.NET as the default JSON serializer in ASP.NET MVC 3 - is it possible? covers how to get MVC to return null for Json(null) - basically, use Json.NET instead of ASP.NET MVC's built-in JSON serializer. This is the solution I ultimately ended up using.

您需要使用答案稍微修改后的版本不过来解决这个问题 - code是如下。基本上,不包括如果语句检查空传递序列化之前,或者你是右后卫在同一predicament。

You need to use a slightly modified version of that answer to fix this however - code is below. Basically, don't include the if statement checking for null before passing to serialize, or you're right back in the same predicament.


的ISO 8601日期的Json.NET的默认实现突破互联网&NBSP;&浏览器NBSP; 9 及以下时,它会尝试与新的日期(...)解析。换句话说,这些分析罚款互联网与NBSP;浏览器&NBSP; 9:

The default implementation of ISO 8601 Dates in Json.NET breaks Internet Explorer 9 and below when it attempts to parse it with new Date(...). In other words, these parse fine in Internet Explorer 9:

var date = new Date('2014-09-18T17:21:57.669');
var date = new Date('2014-09-18T17:21:57.600');

但是,这将引发异常:

But this throws an exception:

var date = new Date('2014-09-18T17:21:57.6');

互联网&NBSP;&浏览器NBSP; 9的日期()实现不能处理任何事情,但正好是三毫秒的地方。为了解决这个问题,你必须覆盖Json.NET的日期格式,迫使它。包括在下面的code。

Internet Explorer 9's Date() implementation can't cope with anything but exactly three millisecond places. To fix this you have to override the Json.NET date format to force it. Included in the code below.

public class JsonNetResult : JsonResult
{
    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
            throw new ArgumentNullException("context");

        var response = context.HttpContext.Response;

        response.ContentType = !String.IsNullOrEmpty(ContentType) ? ContentType : "application/json";

        if (ContentEncoding != null)
            response.ContentEncoding = ContentEncoding;

        var settings = new JsonSerializerSettings
        {
            Converters = new[] {new IsoDateTimeConverter
            {
                DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffK"
            }}
        };
        var jsonSerializer = JsonSerializer.Create(settings);

        jsonSerializer.Serialize(response.Output, Data);
    }
}

这篇关于jQuery的JSON后从ASP.NET MVC返回null时失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆