模型绑定不适用于 System.Drawing 个对象

Model Binding doesn't work with System.Drawing objects

我想将图片设置从页面传递到控制器。我通过 JSON 传递数据。我有如下 JS 对象:

    var fields = this.props.settings;
    var settings = {
        ID: fields.id,
        Title: fields.title,
        Size: {
            Width: fields.size.width,
            Height: fields.size.height
        },
        SizeType: fields.sizeType,
        MimeType: {
            ID: fields.id,
            Title: fields.title,
            Extension: fields.ext
        }};

我通过AJAX发送数据:

        $.ajax({
        url: url,
        type: 'post',
        data: JSON.stringify({ settings: settings }),
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        success: function (message) {
            self.refs.progress.onSuccess(message);
        },
        error: function (message) {
            self.refs.progress.onFailed("Ups... something wrong :(");
        }
    });

我的控制器看起来像:

    public ActionResult ConvertPictures(ConvertSettings settings)

我的模型如下所示:

public class ConvertSettings : IListItem
{
    public int? ID { get; set; }  //OK

    public string Title { get; set; } //OK

    public System.Drawing.Size Size { get; set; } //NOK 

    public SizeType SizeType { get; set; } //OK

    public MimeType MimeType { get; set; } //OK
}

我对 'Size' 属性 有疑问。控制器接收 'Size' 属性 与:

{Height = 0, Width = 0}

我也试过使用矩形 class 但还是有同样的问题。我将 JSON 值解析为 int:

Size: {
        Width: 123,
        Height: 33
    }

但仍然在控制器中,模型有 {Height = 0, Width = 0}。其他属性(ID、枚举等)运行良好。我在我的应用程序中使用 DefaultModelBinder。

Size Structure 没有无参数构造函数,因此 DefaultModelBinder 无法初始化它并设置它的值。

创建您自己的 class 以接收和绑定值(并且使用 System.Drawing 命名空间无论如何在 mvc 应用程序中都不合适),例如

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

并更改 ConvertSettings 以使用它

public class ConvertSettings : IListItem
{
    public int? ID { get; set; }
    public ImageSize Size { get; set; }
    ....
}