2010-11-03 64 views
0

我有一個操作方法需要幾個可選參數。如何從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?

回答

0

您是否嘗試將默認參數設置爲null?你可能也需要設置類型爲空,但我不是100%確定是否需要,但這就是我使用它的方式。

例如:

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

我也許應該注意,這需要.NET 4,但隨後,你沒有指定你正在運行哪個版本。