【问题标题】:Model Binding doesn't work with System.Drawing objects模型绑定不适用于 System.Drawing 对象
【发布时间】:2018-06-19 16:05:30
【问题描述】:

我想将图片设置从页面传递到控制器。我通过 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
}

我的“大小”属性有问题。控制器接收“大小”属性 与:

{Height = 0, Width = 0}

我也尝试过使用 Rectangle 类,但存在同样的问题。我将 JSON 值解析为 int:

Size: {
        Width: 123,
        Height: 33
    }

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

【问题讨论】:

    标签: asp.net-mvc model-binding


    【解决方案1】:

    Size Structure 没有无参数构造函数,因此DefaultModelBinder 无法对其进行初始化并设置其值。

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

    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; }
        ....
    }
    

    【讨论】:

      猜你喜欢
      • 2019-08-27
      • 1970-01-01
      • 2019-07-03
      • 1970-01-01
      • 1970-01-01
      • 2016-06-23
      • 1970-01-01
      • 2015-06-27
      • 1970-01-01
      相关资源
      最近更新 更多