Asp.Net MVC 2 Error DefaultModelBinder using abstract classes

I have a simple Poco model using abstract classes, and it doesn't seem to work with ModelBinder by default for Asp.net MVC 2. One element has several objects in the collection, all of which use the same abstract base class.

Model:

public partial class Item { public virtual ICollection<Core.Object> Objects { get { return _objects; } set { if (value != _objects) { _objects = value; } } } private ICollection<Core.Object> _objects; } public abstract partial class Object { public virtual Item Item { get { return _item; } set { if (!Object.ReferenceEquals(_item, value)) { _item = value; } } } private Item _item; } public partial class TextObject : Object { public virtual string Text { get; set; } } 

Instance:

 var NewItem = new Item(); var TextObject1 = new TextObject { Text = "Text Object Text", Item = NewItem }; List<Core.Object> objects = new List<Core.Object>(){TextObject1}; NewItem.Objects = objects; 

Using the Html.EditorForModel () Default Assistant for this element with one TextObject in the Objects collection, I get this html input field:

 <input class="text-box single-line" id="Objects_0__Text" name="Objects[0].Text" type="text" value="Text Object Text" /> 

When sending back to the controller, I get the message "Unable to create an abstract class" Errormessage from the Default ModelBinder. Obviously, the binder is trying to create this abstract base class. But I donโ€™t know why, since the collection contains only an object of the inherited TextObject type. Is there any other way to get this working without writing a custom Modelbinder?

+4
source share
3 answers

You will need to use a custom mediator or use viewmodels. The model binder only knows about the type that you use as a parameter for your action (contains an abstract class). He then tries to match the values โ€‹โ€‹from the query to this model. The binding agent does not know that it should use some other implementation and what implementation may be.

My advice is to create more affordable models and map them using automapper .

+3
source

Check out DerivedTypeModelBinder in MvcContrib. TypeStamping embeds metadata in the rendering of the view, providing the derived data that is needed to properly invoke an object to instantiate. A longer discussion with links to this

MVC2 Modelbinder for a list of derived objects

+2
source

I think you need to specify in the Item class the Objects collection as ICollection<TextObject> . Otherwise, it would be impossible for the model communications device to understand by default which object it should create. If you decide to create a custom mediator, you need to add a field to the form for each object that indicates its type. Best wishes.

0
source

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


All Articles