如何将整个模型的值返回为“null”来自 ASP.NET MVC 模型绑定器
我有一个带有几个可选参数的操作方法。
这个 ASP.NET MVC 操作方法看起来很简单,但并没有按照我想要的方式工作......
[HttpPost]
public ActionResult UpdateOrder(OrderItem OrderItem, Address ShippingAddress)
{
if (ShippingAddress != null) {
// we have a shipping address
}
}
总是为 ShippingAddress
创建一个 Address
对象,因为 - 嗯 - 就是这样模型活页夹工作。即使表单中缺少 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 - 此属性设置器已过时,因为它的值现在是从 ModelMetadata.Model 派生的。
有没有办法让自定义 ModelBinder 中的整体“模型”返回 null?
I have an action method that takes several optional parameters.
This ASP.NET MVC actionmethod looks simple enough but isn't working as I want....
[HttpPost]
public ActionResult UpdateOrder(OrderItem OrderItem, Address ShippingAddress)
{
if (ShippingAddress != null) {
// we have a shipping address
}
}
An Address
object is always created for ShippingAddress
because - well - thats the way model binders work. Even if ShippingAddress.Address1
, ShippingAddress.City
etc. fields are absent from the Form an object will still be created and passed to the action.
I want a way to make a model binder that returns null for the model if it is deemed to be empty.
A first attempt goes as follows
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;
}
}
Unfortunately this simple solution doesn't work and I get the following error:
InvalidOperationException -This property setter is obsolete, because its value is derived from ModelMetadata.Model now.
Is there a way I can make the overall 'Model' from a custom ModelBinder to return null?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您是否尝试过将默认参数设置为
null
?您可能还需要将类型设置为可为空,但我不能100%确定是否需要它,但这就是我使用它的方式。例如:
我可能应该注意到这需要 .NET 4,但是您没有指定正在运行的版本。
Have you tried setting the default parameter to
null
? You may also need to set the type to nullable as well, but I'm not 100% sure if it's needed, but that's how I use it.For example:
I should probably note that this requires .NET 4, but then, you didn't specify which version you're running on.