如何从ASP.NET MVC模型绑定器返回一个整体模型的值为'null'
问题描述:
我有一个操作方法需要几个可选参数。如何从ASP.NET MVC模型绑定器返回一个整体模型的值为'null'
这ASP.NET MVC actionmethod看起来很简单,但没有工作,我想....
[HttpPost]
public ActionResult UpdateOrder(OrderItem OrderItem, Address ShippingAddress)
{
if (ShippingAddress != null) {
// we have a shipping address
}
}
的Address
对象总是为ShippingAddress
创建,因为 - 好 - 这就是方式,模型联工作。即使ShippingAddress.Address1
,ShippingAddress.City
等字段没有从窗体中,对象仍将被创建并传递给该操作。
我想要一种方法来创建一个模型绑定器,该模型绑定器在模型被视为空时返回null。
第一次尝试去如下
protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
base.OnModelUpdated(controllerContext, bindingContext);
// get the address to validate
var address = (Address)bindingContext.Model;
// if the address is quintessentially null then return null for the model binder
if (address.Address1 == null && address.CountryCode == null && address.City == null)
{
bindingContext.Model = null;
}
}
不幸的是这简单的解决方案不起作用,我收到以下错误:
出现InvalidOperationException - 这个属性的setter方法已经过时了,因为它的价值现在从ModelMetadata.Model派生。
有没有办法让自定义ModelBinder的整体'Model'返回null?
答
您是否尝试将默认参数设置为null
?你可能也需要设置类型为空,但我不是100%确定是否需要,但这就是我使用它的方式。
例如:
public ActionResult UpdateOrder(OrderItem OrderItem, Address? shippingAddress = null)
我也许应该注意,这需要.NET 4,但随后,你没有指定你正在运行哪个版本。