MVC2 Modelbinder for a list of derived objects

I need a list of different (derived) types of objects that work with ModelBinder by default 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 with different derived types, for example

 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 ArrayList implementation, everything becomes well-formed in the form, but modelbinder does not allow the properties of the derived type of the object for me when sending back to ActionResult.

What could be a good solution for the Viewmodel structure to get a list of different types of objects? Having an additional list for each type of object (e.g. List, List, etc.), Apparently, is not a good solution for me, since this is a lot of overhead, both when building a model of the view and when displaying it back in domain model.

Thinking of a different approach to linking all properties in the binding of a custom model, how can I use the data annotation approach here (checking the necessary attributes, etc.) without a lot of overhead?

+3
source share
1 answer

See the Derived Type of ModelBinder in MvcContrib . This allows you to attach a "typestamping" process to derived types - which is automatically processed for you when using the RenderTypedPartial (...) helper. Partial parts of MvcContrib maintain binding state through partial ones, therefore Name / Id prefixes are properly supported on the graph of deep objects. If you use other mechanisms, such as templates, then you will need to handle typestamping yourself. This is explained on the documentation page.

Returning to your questions about how derived types are resolved using ModelBinder, you can register changes to a derived type with attributes in a mechanism similar to WCF KnownTypeAttribute, or you can register at startup. In any case, these options are recorded once and are taken into account for performance reasons.

The model binder also solves this problem so as not to interfere with the annotation / data validation attributes. They will work as you expect them in any other scenario.

+4
source

Source: https://habr.com/ru/post/1303251/


All Articles