我有一个带有几个可选参数的操作方法。
这个 ASP.NET MVC actionmethod 看起来很简单,但没有按我的意愿工作......
[HttpPost]
public ActionResult UpdateOrder(OrderItem OrderItem, Address ShippingAddress)
{
if (ShippingAddress != null) {
// we have a shipping address
}
}
Address
始终为对象创建一个对象,ShippingAddress
因为——嗯——这就是模型绑定器的工作方式。即使FormShippingAddress.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 - 此属性设置器已过时,因为它的值现在派生自 ModelMetadata.Model。
有没有办法让自定义 ModelBinder 的整体“模型”返回 null?