简体   繁体   English

ASP.NET MVC中一个模型的多个自定义模型绑定器

[英]Multiple custom model binders for one model in ASP.NET MVC

This is a general model binding question that applies to MVC 1 & 2. I'm wondering if MVC2 would be better for this, but here's my question: 这是适用于MVC 1和2的通用模型绑定问题。我想知道MVC2是否会对此更好,但这是我的问题:

I have a fairly complex model: 我有一个相当复杂的模型:

public interface IEvent
  public int Id
  public string Title
  public List<EventContact> Contacts
  public List<EventDatesLocations> DatesLocations

public class EventDatesLocations
  public int Id
  public DateTime StartDate
  public DateTime EndDate
  public List<EventLocation> Locations

I have a custom model binder for my IEvent class that does basically all the binding for IEvent. 我为IEvent类提供了一个自定义模型绑定程序,该绑定程序基本上完成了IEvent的所有绑定。 I call the default model binder for binding the Contacts list, which works well. 我将默认模型绑定器称为绑定Contacts列表,这很好用。

I am ready to start trying to bind the DatesLocations stuff, but I want to make sure I'm doing things correctly. 我准备开始尝试绑定DatesLocations东西,但是我想确保自己做的正确。

Overall, I'm not sure I have all the details on model binding understood. 总的来说,我不确定我是否了解模型绑定的所有细节。 Would it be better to have multiple model binders for the lists within IEvent or just have one IEvent model binder (as I'm doing now) which calls the default binder for the lists it needs. 最好在IEvent为列表使用多个模型IEvent还是仅使用一个IEvent模型联编程序(就像我现在所做的那样),后者为所需的列表调用默认联编程序。

How do the experts do it? 专家们是如何做到的? :P :P

Take a look at this question to see some nested model binding. 看一下这个问题 ,看一些嵌套的模型绑定。

Back to this question, you mention you need to do some binding on different implementations of IEvent, but then you want to bind specific properties depending on what type implements IEvent. 回到这个问题,您提到您需要对IEvent的不同实现进行一些绑定,但是然后您想要根据实现IEvent的类型绑定特定的属性。 I would say this is generally bad. 我会说这通常是不好的。 Why? 为什么? Because you are trying to get one model binder knowing about an Interface knowing about specific implementations of it. 因为您正在尝试让一个模型绑定程序知道一个接口,而该接口又知道它的特定实现。

If you require multiple classes to implement IEvent (for some reason) then you will probably need custom binders for each (if going down this route, although as they will be concrete types then the default binder should work), or you need to expand the IEvent interface to include the properties you will be setting on all. 如果您需要多个类来实现IEvent(出于某种原因),则可能需要为每个类自定义活页夹(如果走这条路,尽管它们是具体类型,则默认活页夹应该可以工作),或者您需要扩展IEvent接口包含您将要在所有属性上设置的属性。

Remember Interfaces are there to define a contract that needs to be implemented ... you can't work with objects which implement it and then check for other properties depending on what type they are :-) 请记住,接口在那里定义了需要实现的契约...您不能使用实现该契约的对象,然后根据它们是什么类型来检查其他属性:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM