0

我有一个带有几个可选参数的操作方法。

这个 ASP.NET MVC actionmethod 看起来很简单,但没有按我的意愿工作......

[HttpPost]
public ActionResult UpdateOrder(OrderItem OrderItem, Address ShippingAddress)
{
     if (ShippingAddress != null) {
         // we have a shipping address
     }
}

Address始终为对象创建一个对象,ShippingAddress因为——嗯——这就是模型绑定器的工作方式。即使FormShippingAddress.Address1ShippingAddress.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?

4

1 回答 1

0

您是否尝试将默认参数设置为null?您可能还需要将类型设置为可为空,但我不能 100% 确定是否需要它,但这就是我使用它的方式。

例如:

public ActionResult UpdateOrder(OrderItem OrderItem, Address? shippingAddress = null)

我可能应该注意到这需要 .NET 4,但是,您没有指定正在运行的版本。

于 2010-11-03T13:35:27.410 回答