我想将图片设置从页面传递到控制器。我通过 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}
我也尝试过矩形类,但存在同样的问题。我将 JSON 值解析为 int:
Size: {
Width: 123,
Height: 33
}
但仍在控制器中,模型具有 {高度 = 0,宽度 = 0}。其他属性(ID,枚举等)工作良好。我在应用程序中使用 DefaultModelBinder。
大小结构没有无参数构造函数,因此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; }
....
}