devmiles.com
devmiles.com

Reputation: 10014

WebApi and MVC controllers

I'm planning to have both MVC and WebAPI functionality in my application. There's going to be an administration site implemented with simple MVC CRUD controllers and I also need a RESTful API to be called from the remote client and possibly from a single page app in the future. I'm not too comfortable with writing very similar classes that differ only in return type - MVC controllers returning data wrapped in a View and WebAPI controllers simply returning data unwrapped. What would be the best way to achieve my goals without repeating too much code?

Upvotes: 1

Views: 1059

Answers (2)

sellmeadog
sellmeadog

Reputation: 7517

In my opinion, if you're using WebAPI, your standard MVC controllers shouldn't be used for CRUD. Your API controllers should handle CRUD operations and your MVC controllers should return views.

By going this route, it gives you a couple of different options as to how you'll display data in your views:

TRADITIONAL

If you want to stick with a more "traditional" route, you can invoke your WebAPI controllers server side from your MVC controller, hydrate a model object and return a strongly typed view. You can do this by using the HttpClient class or the WebClient class to make your API calls and deserializing the response.

SINGLE PAGE

If you want to try a more "modern" route, you can try what danludwig suggested and build more of a single page app. In this scenario, your MVC controller will just return a HTML + JavaScript view that relies on a client-side framework to make API calls and update the DOM. The require + backbone + knockback/knockout stack is a great place to start but it does have a bit of a learning curve.

Either way, you really should only have CRUD logic in one place, and I believe this belongs in the API.

Upvotes: 5

danludwig
danludwig

Reputation: 47375

One way would be to have your MVC controllers not return strongly typed viewmodels. Instead they could return plain HTML + javascript that could use something like backbone or knockout to invoke your Api action methods and populate the DOM.

Upvotes: 1

Related Questions