从控制器返回PartialView时出现JSON.parse错误 [英] JSON.parse error upon returning PartialView from controller

查看:69
本文介绍了从控制器返回PartialView时出现JSON.parse错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下ajax调用

    $.ajax({
        type: "POST",
        url: url,
        dataType: "json",
        data: { occupants: occupants },
        success: function (data) {
            $("#summaryContent").html(data);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("Status: " + textStatus);
            console.log("Error: " + errorThrown);
        }
    });

还有一个看起来像这样的控制器

And a controller that looks like this

    [HttpPost]
    public PartialViewResult Verification(List<OccupantDto> occupants)
    {
        //do stuff
        return PartialView();
    }

我在ajax调用中遇到此错误

And I'm getting this error in my ajax call

Error: SyntaxError: JSON.parse Error: Invalid character at position:5

我尝试从ajax调用中删除 dataType:"json" ,这消除了错误,并呈现了我的局部视图,但是,在我的控制器中, occupants 是一个空列表.添加 dataType:"json" 会在控制器中填充占用者,但会引发错误.

I tried removing dataType: "json" from my ajax call, that removes the error, and it renders my partial view, however, in my controller, occupants is an empty list. Adding dataType: "json" populates occupants in my controller, but throws me an error.

推荐答案

您的 $.ajax 方法调用中的这一部分

This part in your $.ajax method call

dataType: "json",

告诉jQuery您期望服务器的结果为有效的json字符串.因此,jQuery将尝试将其明确解析为js对象(使用 JSON.parse()方法),并假设它是有效的JSON字符串响应,因为 您向jQuery 保证使用 dataType:"json" 选项.

tells jQuery that you are expecting the result from server as a valid json string. So jQuery will try to explicitly parse it to a js object (using JSON.parse() method) with the assumption that it is a valid JSON string response came back because you assured jQuery that using the dataType: "json" option.

但是,在您的情况下,您将返回视图结果,这只是HTML标记.因此无法将其解析为javascript对象.如果要解析的字符串不是有效的JSON,则 JSON.parse()将引发SyntaxError异常.那就是您得到的,因为parse方法调用崩溃了,因此它执行了 $.ajax 方法的 error 处理程序.

But in your case you are returning a view result, which is just HTML markup. So it cannot be parsed to a javascript object. JSON.parse() will throw a SyntaxError exception if the string to parse is not valid JSON. That is what you are getting because the parse method call crashed, hence it executes the error handler of your $.ajax method.

只需删除指定 dataType 行的那一行.这应该工作

Simply remove that line which specifies the dataType line. This should work

$.ajax({
    type: "POST",
    url: url,
    data: { occupants: occupants },
}).done(function (data) {
    $("#summaryContent").html(data);
}).fail(function (XMLHttpRequest, textStatus, errorThrown) {
    console.log("Status: " + textStatus);
    console.log("Error: " + errorThrown);
});

在大多数情况下,您不必指定 dataType 属性值.如果未指定任何内容,则jQuery将尝试根据返回的MIME类型来推断它.

In most of the cases, you do not need to necessarily specify the dataType property value. If nothing is specified jQuery will try to infer it based on the mime type of the response coming back.

现在,只要您有一个有效的项目数组(与 OccupantDto 的结构匹配),您的 occupants 参数就会被模型绑定程序正确映射,并且不是空/空集合.

Now, As long as you have a valid array of items (matching with the structure of OccupantDto), Your occupants parameter will be properly mapped by model binder and will not be null/empty collection.

假设 OccupantDto 具有 Id Name 属性(已设置表公共属性),则应工作

Assuming OccupantDto has an Id and Name property (which is settable public properties), This should work

var occupants = [{ name: "Scott",id:4},{ name: "Shyju",id:6}];
$.ajax({
    type: "POST",
    url: '@Url.Action("Verification")',
    data: { occupants: occupants }
})

从jQuery 3.0开始,删除了 success() error() complete()回调.您可以改用 done() fail() always().

As of jQuery 3.0, the success(), error() and complete() callbacks are removed . You may use done(), fail(), and always() instead.

这篇关于从控制器返回PartialView时出现JSON.parse错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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