Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a Controller method which is accepting two models?

It seems perfectly valid if we have a API controller with a method like below:

[HttpPost] 
public IHttpActionResult DoStuff([FromBody]ModelA modelA, [FromBody]ModelB modelB)

Note the two [FromBody] attribute.

The question is, how to call such a method ?

localhost/test/DoStuff/

POST Data:

<?xml version="1.0"?>
<ModelA>
 ...
</ModelA>
<ModelB>
 ...
</ModelB>

does not seem to be recognized. Any ideas why ?

EDIT: The error data is like below:

<?xml version="1.0"?>
<Error>
  <Message>An error has occurred.</Message>
  <ExceptionMessage>Can't bind multiple parameters ('model1' and 'model2') to the request's content.
  </ExceptionMessage>
</Error>
like image 658
now he who must not be named. Avatar asked Sep 17 '14 11:09

now he who must not be named.


2 Answers

I would say that instead of justifying this lack of support of multiple models with documentation, you should find an argument in terms of software architecture perspective: ASP.NET Web API is built on top of MVC paradigm, where a view is bound to a model and handled by a controller.

In other words: 1 Model, 1 View, 1 Controller.

Your use case shouldn't be solved with 2 models, but using a DTO. Instead of binding 2 parameter to 2 models, design a DTO which includes both models as associations of the whole DTO:

// You don't need [FromBody] since complex types are already taken
// from the request body
public IHttpActionResult DoStuff(SomeDto dto)
like image 68
Matías Fidemraizer Avatar answered Sep 23 '22 19:09

Matías Fidemraizer


Create a ViewModel which consists of two models and use it as a single Model in your controller.

public class MergedModel
{
    public ModelA A{get; set;}
    public ModelB B{get; set;}
}
like image 29
mrsrizan Avatar answered Sep 20 '22 19:09

mrsrizan