我的操作采用一个由默认模型绑定器绑定的类属性:
public ActionResult MyControllerAction(MyModelClass model) { ...
该类使用几种非标准值类型,例如 MongoDB 的 ObjectId
值类型,它当然是不可为 null 的。
如果我为 ObjectId 类型创建一个自定义模型绑定程序(很容易做到)并将其添加到 Application_Start
中,如下所示:
ModelBinders.Binders.Add(typeof(ObjectId), new ObjectIdModelBinder());
...它会被默认模型绑定程序忽略,这似乎只是适用于作为参数直接传递给操作的模型值。
最重要的是,我似乎无法获得 [Required]
属性来识别尚未提供的默认(未指定)值。
简而言之:
- 如何让默认模型绑定器使用注册的自定义模型绑定器来解析模型的属性?
- 如何让
[Required]
将该属性的default
值识别为尚未指定?
或者——是否已经有一些东西可以处理所有这些,我可以下载并在我的项目中使用?
My action takes a class property which is bound by the default model binder:
public ActionResult MyControllerAction(MyModelClass model) { ...
The class uses several non-standard value types, such as MongoDB's ObjectId
value type, which is of course non-nullable.
If I create a custom model binder for the ObjectId type (easy enough to do) and add it to the in Application_Start
like so:
ModelBinders.Binders.Add(typeof(ObjectId), new ObjectIdModelBinder());
... it is ignored by the default model binder, which only seems to apply to model values passed in as an argument directly to the action.
On top of this, I can't get seem to get the [Required]
attribute to recognise the default (not specified) value as having not been supplied.
So in a nut shell:
- How do I get the default model binder to use the registered custom model binders to parse a model's properties?
- How do I get
[Required]
to recognise the default
value of that property as not having been specified?
Or -- is there something already out there which already handles all of this which I can download and use in my project?
发布评论
评论(1)
好的,已经弄清楚了:
DefaultModelBinder
确实使用任何指定的自定义模型绑定程序,但前提是该值实际上在提交的值中指定了[必需]< /code> 属性基本上是“not null”的简写,因此如果该属性被指定为可空,则它会起作用,即在我的例子中,如果没有指定值,
ObjectId?
将触发该属性。这是我发现的一篇很好的博客文章,解释了其中的一些内容: http://bradwilson.typepad.com/blog/2010/01/input-validation-vs-model-validation-in-aspnet-mvc.html
Ok, figured it out already:
DefaultModelBinder
does use any specified custom model binders, but only if the value is actually specified in the submitted values[Required]
attribute is basically shorthand for "not null", and therefore does work if the property is specified as nullable, i.e. in my case,ObjectId?
will trip up the attribute if no value is specified.Here's a good blog post I found that explains some of this stuff: http://bradwilson.typepad.com/blog/2010/01/input-validation-vs-model-validation-in-aspnet-mvc.html