ASP.. NET MVC 5模型绑定不起作用
本文关键字:绑定 不起作用 模型 NET MVC ASP | 更新日期: 2023-09-27 18:17:36
我有一个模型,我试图通过jQuery的ajax方法传递给控制器
模型如下:
public class Package
{
public string Name;
public int? Length;
public int? Width;
public int? Height;
public int Weight;
public bool IsFragile;
public string Description;
public PackageType Type;
public int? Volume
{
get
{
if (Height != null && Width != null && Length != null)
{
return (int) Height*(int) Width*(int) Length;
}
return null;
}
}
}
我的ajax请求是这样完成的:
$.ajax({
type: "POST",
url: "/Package/Save",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(this.package),
success: function (data) {
self.success('Thank you. Your package has been saved successfully!');
},
error: function () {
self.error('Ooops, something went terribly wrong when saving this package. Please give us a few minutes to fix it!');
}
});
向服务器发送以下内容:
{"Name":"asasdas","Length":"15","Width":"31","Height":"326","Weight":"65","IsFragile":false,"Description":"asdasdasdasd","MyType":0,"Volume":null,"Type":"2"}
我的控制器接收到请求,但参数"savedPackage"的所有属性都设置为默认值:
[HttpPost]
public JsonResult Save(Package savedPackage)
{
return Json(new {test = true});
}
将公共字段改为属性:
public class Package
{
public string Name { get; set; }
public int? Length { get; set; }
public int? Width { get; set; }
public int? Height { get; set; }
public int Weight { get; set; }
public bool IsFragile { get; set; }
public string Description { get; set; }
public PackageType Type { get; set; }
public int? Volume
{
get
{
if (Height != null && Width != null && Length != null)
{
return (int) Height*(int) Width*(int) Length;
}
return null;
}
}
}
参见这个问题