Question

I have got following class hierarchy in my ASP MVC 3 project. Some entry can have containers, and that containers can have some content inside. Container and content classes are abstract classes.

Hierarchy

I need to receive json request from browser, and bind it to model which is type of Entry class. The problem is that DefaultModelBinder class didn't correctly create the Entry model class because it didn't know what type of concrete container it should be. For example:

var dataaa = { Name: 'Some Name', Containers: [{ ContainerId: 0}] };
    $.ajax({
        url: 'Add',
        type: "POST",
        data: JSON.stringify(dataaa),
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            alert('hello');
        });

+

[HttpPost]
public string Add(Entry entry)
{
    return "foo";
}

Following request leads to server exception: Cannot create an abstract class. I can add Type field to json request for example:

{ Name: 'Some Name', Containers: [{ Type: 'FullContainer', ContainerId: 0}] }; 

How to instruct the model binding mechanism to map the object which got Type field set to 'FullContainer' to FullContainer class?

Was it helpful?

Solution 2

I have posted an answer on my hompage.

OTHER TIPS

Is Entry a view model? Are the properties contained within the base Entry sufficient for your post, even if it's of type Full Container? If it's not a view model, but it's all you truly need, I'd advise making an EntryViewModel class that isn't abstract.

Otherwise, check out Darin's answer here Polymorphic model binding.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top