ASP.NET MVC and AngularJS
I really think these two frameworks don’t mesh together too well and this blog post is me trying to explain why.
If you’re used to traditional MVC with full page refreshes, views, server side partials etc. and you’ve decided that you want to use a bit of angular inside your pages you are going to be very frustrated. Angular is really best for single page applications (SPA seems to be a buzz word for the moment). If you just want some javascript goodness just use knockoutjs.
I’d suggest using WebApi instead. This is what I’ve found out works best.
- The server side actions on the ApiController should only return JSON data to the client and be consumed by ajax calls from angular.
- Stop thinking in terms of razor and writing C# code in your views and working with the @model passed from the controller.
- Only have one razor page for your app (Index.cshtml), no views, no partials. Load everything on the index page.
- Do not use the MVC routing, let angular perform the dynamic page updates.
You might ask yourself; why use razor at all? Well the Web.Optimization bundle is quite neat and I’ve grown quite attached to it :-)
For SPAs sure go ahead and use angular it’s awesome. But stick with angular/javascript for front-end and use WebApi for back-end if you’ve decided that you want to try out angular on top of asp.net.
Also imo SPAs should be fairly small, if you know your project will be fairly big SPA really isn’t the way to go. It could be me just having a hard time to adapt since I’m used to hooking everything up in a spaghetti of document.ready-functions :-P I’ve always been a “back-end / do it on the server / use as much static typing as possible” kind of guy but perhaps that’s changing, especially with tools like TypeScript which is a must in all my web projects nowadays.
I might add that I also have experience using angular together with jQuery mobile when developing a scorecard app for golf (golf-caddie.se) which wasn’t too pleasant but that’s another blog post (two frameworks manipulating the DOM don’t play nice together).
Just my thoughts, it’s not written in stone :D