title: MVC5.1 with Web API 2 and AngularJS
body: <p>I am working on a side project to teach myself AngularJS and Web API and how the two can work together nicely.</p>
  
  <p>I have good ASP.NET MVC knowledge, but I still can't get my head around AngularJS and Web API and how all three can work together.</p>
  
  <p>At the moment, I have a Web API Controller with the following code:</p>
  
  <pre><code>public class PlanController : ApiController
  {
      [Route("api/thing")]
      public HttpResponseMessage Post(ThingVM model)
      {
          HttpResponseMessage response;
  
          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;
      }
  }
  </code></pre>
  
  <p>In my <code>Create.cshtml</code> view I have the <code>ng-app</code> directive and I have created a JS controller and placed the <code>ng-controller</code> directive around the form, and have pointed it at the JS controller.</p>
  
  <p>But here I am stuck. First of all, how do I bind my <code>ThingVM.cs</code> ViewModel to Angular? Do I need to return a <code>JSONResult</code> on my MVC controller? If Yes, how? Cause I tried, the following, and it isn't compiling.</p>
  
  <pre><code>[HttpGet]
  public JsonResult Create()
  {
      using (var context = new MyContext())
      {
          var model = new ThingVM();
          return Json(model);
      }
  }
  </code></pre>
  
  <p>Assuming I get that to work, how do I bind it to AngularJS, so that it knows what my ViewModel structure is like? Because my <code>ThingVM</code> has many levels of complexity.</p>
  
  <p>Finally, how do I handle the form submission, so that angular points at my Web API Controller for the <code>POST</code> request.</p>