简体   繁体   中英

MVC3 Binding an Object property that inherits from a base class

I am trying to find out if what I want to do is possible when posting a form to the controller.

Assume my class:

    public class ObjectToBeBound {
      public int Id {get;set;}
      public List<BaseObject> Items {get;set;}
    }

    public class Child1 : BaseObject {
     public string ExtraField {get;set;}
     }

    public class Child2 : BaseObject {
     public string OtherField {get;set;}
     }

On the page, the Items property will be a mix of "Child1" and "Child2" objects. However, when I post the form, since the property is defined as a list of "BaseObject"s, I only get the fields that are defined on "BaseObject."

I looked into creating a custom model binder, but I couldn't figure out if it's possible to bind an object's property specifically so I could bind Item[0] as Child1 and Item[1] and Item[2] as Child2. I only saw ways to give the entire "ObjectToBeBound" object a specific type.

I could manually assign each property in a custom model binder, but I'm wondering if there's an easier way I'm missing. Any ideas?

I think you can use reflection to find out the type of the object in the list, and then you can cast to the specific Child. After the cast you should be able to use the child object properties

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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