4

我正在使用 ASP.NET MVC 3,并且正在尝试将简单的 json 数组绑定到List<JsonPositions>. JsonPositions是一个自定义对象,与数组中的 json 对象具有相同的属性。

这是我的数组在客户端上的样子:

var widgetPositions = [
    { col: 5, row: 1, id: 2 },
    { col: 4, row: 5: id: 40 }
];

$.ajax({
    url: 'the url',
    data: { positions: widgetPositions },
    success: function () {
        alert('Save successful.');
    },
    error: function () {
        alert('An error occurred while trying to update the widget positions.');
    }
});

在 Chrome 中检查请求时,此代码似乎工作正常。

在控制器中,我们有以下操作方法:

public void UpdatePositions(List<JsonPosition> positions)
{
    // debugging here
}

当我检查widgetPositions列表时,它确实有两个项目,就像 json 数组一样,但是对象的属性与客户端上对象的值不匹配。这是对象的JsonPosition样子:

public class JsonPosition
{
    public int id { get; set; }
    public int col { get; set; }
    public int row { get; set; }
}

谢谢你的尽心帮助 :)

4

2 回答 2

3

我认为您可能需要添加内容类型:

$.ajax({
    url: 'the url',
    data: JSON.stringify({ positions: widgetPositions }),
    contentType: 'application/json',
    success: function () {
        alert('Save successful.');
    },
    error: function () {
        alert('An error occurred while trying to update the widget positions.');
    }
});

此外,您没有指定请求类型,因此默认情况下它会执行 GET,您的意思是执行 POST 吗?那会让它

$.ajax({
    url: 'the url',
    type: 'POST',
    data: JSON.stringify({ positions: widgetPositions }),
    contentType: 'application/json',
    success: function () {
        alert('Save successful.');
    },
    error: function () {
        alert('An error occurred while trying to update the widget positions.');
    }
});
于 2012-08-15T16:23:51.917 回答
2

您可以将它们作为 JSON 对象发送:

var widgetPositions = [
    { col: 5, row: 1, id: 2 },
    { col: 4, row: 5: id: 40 }
];

$.ajax({
    url: 'the url',
    data: JSON.stringify({ positions: widgetPositions }),
    contentType: 'application/json',
    success: function () {
        alert('Save successful.');
    },
    error: function () {
        alert('An error occurred while trying to update the widget positions.');
    }
});

需要注意的事情是你的代码中没有,这将使它工作:

  • contentType: 'application/json',- 设置正确的请求内容类型标头
  • data: JSON.stringify({ positions: widgetPositions })- 发送 JSON 请求

现在你会很高兴在这里得到你需要的一切:

public void UpdatePositions(List<JsonPosition> positions)
{
    // debugging here
}

备注:该JSON.stringify方法在所有现代浏览器中都原生定义(即使在 IE8 中,即使这远非现代浏览器)。但是如果您需要支持一些史前浏览器,您可以在页面中包含json2.js脚本,该脚本将检查浏览器是否原生支持此方法,如果不提供实现。

于 2012-08-15T16:51:14.477 回答