I am working on a side project to teach myself AngularJS and Web API and how the two can work together nicely.
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.
At the moment, I have a Web API Controller with the following 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;
}
}
In my Create.cshtml
view I have the ng-app
directive and I have created a JS controller and placed the ng-controller
directive around the form, and have pointed it at the JS controller.
But here I am stuck. First of all, how do I bind my ThingVM.cs
ViewModel to Angular? Do I need to return a JSONResult
on my MVC controller? If Yes, how? Cause I tried, the following, and it isn't compiling.
[HttpGet]
public JsonResult Create()
{
using (var context = new MyContext())
{
var model = new ThingVM();
return Json(model);
}
}
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 ThingVM
has many levels of complexity.
Finally, how do I handle the form submission, so that angular points at my Web API Controller for the POST
request.