MVC2 Modelbinder for List of derived objects

Posted by user250773 on Stack Overflow See other posts from Stack Overflow or by user250773
Published on 2010-03-10T11:21:36Z Indexed on 2010/03/29 19:43 UTC
Read the original article Hit count: 255

I want a list of different (derived) object types working with the Default Modelbinder in Asp.net MVC 2.

I have the following ViewModel:

public class ItemFormModel
    {       
        [Required(ErrorMessage = "Required Field")] 
        public string Name { get; set; }
        public string Description { get; set; }

        [ScaffoldColumn(true)]
        //public List<Core.Object> Objects { get; set; }       
        public ArrayList Objects { get; set; }                  
    }

And the list contains objects of diffent derived types, e.g.

public class TextObject : Core.Object
    {
        public string Text { get; set; }
    }

    public class BoolObject : Core.Object
    {
        public bool Value { get; set; }
    }

It doesn't matter if I use the List or the ArrayList implementation, everything get's nicely scaffolded in the form, but the modelbinder doesn't resolve the derived object type properties for me when posting back to the ActionResult.

What could be a good solution for the Viewmodel structure to get a list of different object types handled? Having an extra list for every object type (e.g. List, List etc.) seems to be not a good solution for me, since this is a lot of overhead both in building the viewmodel and mapping it back to the domain model.

Thinking about the other approach of binding all properties in a custom model binder, how can I make use the data annotations approach here (validating required attributes etc.) without a lot of overhead?

© Stack Overflow or respective owner

Related posts about asp.net-mvc2

Related posts about modelbinders