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