3

I am looking at how to bind a model to a derived class within MVC Web API, the issue I have is that I think I have found about 5 ways of doing it...

What I have is:

Models ->

  • ModelBase
  • ModelA : ModelBase
  • ModelB : ModelBase

Controller then containers the method:

Post(ModelBase model) {}

The data that is posted will be ModelA or ModelB, I want to add information to the HTTP Request metadata (think Content-Type: application/json; type=ModelA) and based on this tell MVC to bind the posted content to either A or B.

In code I imagine something like:

Bind(request, bindingContext)
{
    // check request headers and then...
    bindingContext.ModelType=typeof(ModelA);

    // let the framework continue doing its thing deserializing the content
    base.Bind(request, bindingContext);
}

How has everyone else does this? Or how would you recommend doing this?

I've seen ParameterBinding, IModelBinder, MediaTypeFormatter, etc. MVC is great, but sometimes its hard to think which hook you should use...

EDIT:

To add more information, the ModelBase will most likely become an interface, and there will be hundreds of concrete classes.

It is going to be for CQRS: Command and then the ConcreteCommandA, ConcreteCommandB, these will get pushed off to a dispatcher, I don't want to be making an action for each command, a central action to receive these commands, deserialize them to the correct type and forward them on.

  • What value is `Post(ModelBase model)` when you have to cast it down to the more derived type anyway? Why not just `Post(ModelA model)` and so forth? – Haney Jun 09 '14 at 16:26
  • why dont you just seperate it into 3 methods. 1 with ModelA argument, 1 with Model B argument and the 3rd a private method which contains the shared logic. Don't overcomplicate it :) – heymega Jun 09 '14 at 16:33
  • Link to a similar question that might help (not a duplicate): http://stackoverflow.com/questions/24413491/resolving-interfaces-in-webapi. – djikay Jun 25 '14 at 22:11
  • Have you seen this question: http://stackoverflow.com/questions/8030538/how-to-implement-custom-jsonconverter-in-json-net-to-deserialize-a-list-of-base? It might give you some ideas. – djikay Jun 26 '14 at 09:56

0 Answers0