如何防止模型绑定器中关系的验证?
举个例子,如果我有一个名为 Order 的类,其中有一个引用客户的字段,然后有一个带有下拉列表的订单表单 (<%= Html.DropDownListFor(e => e.Customer.ID, new SelectList(. ..)) %>) 为了设置 Customer,模型绑定器将创建一个仅包含 ID 集的空 Customer。这对于 NHibernate 来说工作得很好,但是当将验证添加到 Customer 类的某些字段时,模型绑定器会说这些字段是必需的。如何阻止模型绑定器验证这些引用?
谢谢!
An example, if I have a class named Order with a field referencing a Customer, and then an Order form with an drop down list (<%= Html.DropDownListFor(e => e.Customer.ID, new SelectList(...)) %>) for setting the Customer the model binder will create an empty Customer with only the ID set. This works fine with NHibernate but when validation is added to some of the fields of the Customer class, the model binder will say these fields are required. How could I prevent the model binder from validating these references?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
老问题了,但我想我无论如何都会为后代回答。在这种情况下,您需要一个自定义模型绑定器来在尝试绑定该属性之前拦截该属性。默认模型绑定器将递归地尝试使用其自定义绑定器绑定属性,如果未设置,则使用默认绑定器。
您在 DefaultModelBinder 中寻找的覆盖是 GetPropertyValue。这是在模型中的所有属性上调用的,默认情况下它回调到 DefaultModelBinder.BindModel - 整个过程的入口点。
简化模型:
视图:
模型绑定器:
请注意,在视图中我们为 model.foo.bar 创建了 DropDownList。Id< /强>。在模型绑定器中,确保将其也添加到模型名称中。您可以将其保留在两者中,但是 DropDownListFor 在查找所选值时会遇到一些问题,而无需在发送的 SelectList 中预先选择它。
最后,回到控制器中,确保将此属性附加到您的数据库上下文中(如果您使用实体框架,其他人可能会以不同的方式处理)。否则,它不会被跟踪,并且上下文将尝试在保存时添加它。
控制器:
Ages old question, but I figured I'd answer anyways for posterity. You need a custom model binder in this situation to intercept that property before it attempts to bind it. The default model binder will recursively attempt to bind properties using their custom binder, or the default one if not set.
The override you're looking for in DefaultModelBinder is GetPropertyValue. This is called over all properties in the model, and by default it calls back to DefaultModelBinder.BindModel - the entry point to the whole process.
Simplified model:
View:
Model Binder:
Note that in the View we create the DropDownListFor the model.foo.bar.Id. In the model binder, ensure that this is added to the model name as well. You can leave it off of both, but then DropDownListFor has a few issues finding the selected value without pre-selecting it in the SelectList you send it.
Finally, back in the controller, be sure to attach this property in your database context (if you're using Entity Framework, others might handle differently). Otherwise, it isn't tracked and the context will attempt to add it on save.
Controller: