MVC5.1 with Web API 2 and AngularJS MVC5.1 with Web API 2 and AngularJS angularjs angularjs

MVC5.1 with Web API 2 and AngularJS


In MVC SPA like angular, you should separate models from views. I would suggest that your asp.mvc is where you serve your views (HTML) and your asp.net web api is where you serve your models (JSON) with CRUD operations.

Your asp.net mvc controller:

[HttpGet]public ActionResult Create(){    return View(); //this return Create.cshtml}

Your asp.net api controller:

public class PlanController : ApiController{    public ThingVM Get()    {        using (var context = new MyContext())        {            var model = new ThingVM();            return model;        }    }    public HttpResponseMessage Post(ThingVM model)    {        HttpResponseMessage response;        //It's better to write the modelstate validation as an attribute. See improvement suggestion below        if (ModelState.IsValid)        {            using (var context = new MyContext())            {                var thing = new Thing();                context.Thing.Add(thing);                context.SaveChanges();                response = Request.CreateResponse(HttpStatusCode.Created);                string uri = Url.Link("GetThingById", new {id = thing.Id});                response.Headers.Location = new Uri(uri);            }        }        else        {            response = Request.CreateResponse(HttpStatusCode.BadRequest);        }        return response;    }}

Your angular controller, here I use $http for quick demonstration. In real app, you could try angular resource to create a REST client

app.controller("planController", function ($scope, $http){    $scope.thingVM = $http.get("api/Plan"); //load view model as json from web api    $scope.saveThingVM = function(){          http.post("api/Plan",$scope.thingVM); //send a post request to web api to update     }});

Your Create.cshtml could be like this:

<form ng-submit="saveThingVM()" ng-controller="planController">   <input ng-model="thingVM.Name" type="text"></input>   <input type="submit">Save model</input></form>

Improvement suggestion:

Model validation is a cross-cutting concern, it's better to write the logic as an attribute to reuse the logic. Take a look at my another answer at How can I centralize modelstate validation in asp.net mvc using action filters?