有没有办法让 DefaultModelBinder 在绑定到 List时忽略空项?
我有一个场景,我想更改 DefaultModelBinder 绑定到枚举列表的方式的行为。
我有一个枚举...
public enum MyEnum { FirstVal, SecondVal, ThirdVal }
和一个模型类...
public class MyModel
{
public List<MyEnum> MyEnums { get; set; }
}
并且 POST 正文是...
MyEnums=&MyEnums=ThirdVal
目前,在模型绑定之后,MyEnums 属性将包含...
[0] = FirstVal
[1] = ThirdVal
是否有一种方法可以告诉模型绑定程序忽略发布的数据中的空值,以便 MyEnums 属性看起来像下面这样?
[0] = ThirdVal
I have a scenario where I'd like to change the behavior of the DefaultModelBinder in how it binds to a List of enums.
I have an enum...
public enum MyEnum { FirstVal, SecondVal, ThirdVal }
and a class for a model...
public class MyModel
{
public List<MyEnum> MyEnums { get; set; }
}
and the POST body is...
MyEnums=&MyEnums=ThirdVal
Currently, after model binding, the MyEnums property will contain...
[0] = FirstVal
[1] = ThirdVal
Is there was a way to tell the model binder to ignore the empty value in the posted data so that MyEnums property could look like the following?
[0] = ThirdVal
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以为 MyModel 编写一个自定义模型绑定器:
它在
Application_Start
中注册:更新:
根据评论部分的要求,以下是如何使以前的绑定器更通用:
You could write a custom model binder for MyModel:
which is registered in
Application_Start
:UPDATE:
As requested in the comments section here's how to make the previous binder more generic: