1

我正在使用 jquery 插件 Jcrop 进行自定义图像大小调整,并且在将数据传递给 MVC 时遇到问题,它会在将参数传递给方法调用时正确解释它。

这是我的 Ajax 调用的样子

var cropArea = { X: 50, Y: 50, Width: 200, Height: 200 };
var destSize = { Width: 200, Height: 200 };
$.ajax ({
    url: "image/CropImage",
    type: "POST",
    data: JSON.stringify({ id: image.id, cropArea: cropArea, size: destSize }),
    dataType: "json"
});

C# 代码看起来像这样

[HttpPost]
public ActionResult ResizeImage(int id, Rectangle cropArea, Size size)
{
    // Crop Code here
}

Id 很好,但 Rectangle 和 Size 对象不会,我只是收到一个cropArea 和 size 的空异常错误。我可以将矩形和大小参数作为数组传递,但我宁愿将矩形和大小对象传入

4

1 回答 1

0

您的 jquery ajax 代码缺少contentType参数:

var cropArea = { X: 50, Y: 50, Width: 200, Height: 200 };
var cropArea = { X: 50, Y: 50, Width: 200, Height: 200 };
var destSize = { Width: 200, Height: 200 };
$.ajax({
    url: "image/CropImage",
    type: "POST",
    data: JSON.stringify({ id: image.id, cropArea: cropArea, size: destSize }),
    dataType: "json",
    contentType: 'application/json; charset=utf-8'
});

我已经快速测试了在我的家庭控制器和一些虚拟类中使用虚拟方法:

[HttpPost]
public ActionResult ResizeImage(int id, Rectangle cropArea, Size size)
{
    // Crop Code here
    return Json(true);
}

public class Rectangle
{
    public int X { get; set; }
    public int Y { get; set; }
    public int Width { get; set; }
    public int Height { get; set; }
}

public class Size
{
    public int Width { get; set; }
    public int Height { get; set; }
}

当我单击按钮时使用此代码发布:

$("#test").click(function () {
    var cropArea = { X: 50, Y: 50, Width: 200, Height: 200 };
    var destSize = { Width: 200, Height: 200 };
    $.ajax({
        url: "/Home/ResizeImage",
        type: "POST",
        data: JSON.stringify({ id: 210, cropArea: cropArea, size: destSize }),
        dataType: "json",
        contentType: 'application/json; charset=utf-8'
    });
});

希望能帮助到你!

于 2013-06-26T18:58:40.360 回答