Angular and ASP.NET MVC: when to use which golden hammer

In my previous post, I outlined how to use ASP.NET MVC and Angular together, making certain views pure MVC and others Angular.

When I first used Angular this way, I was so happy, I went the full Angular way making requests from Angular for my data. Essentially, something like this:

$http({  
    method: 'GET',
    url: '/api/rest/'
}).success(function (data, status, headers, config) {
    vm.names = data;
}).error(function (data, status, headers, config) {

});

This is code inside my customers.js. It's just a call to my RestController.cs (a WebAPI controller). In my customers.html template, I have a simple:

<li ng-repeat="name in vm.names">{{name}}</li>

But now, we're making two requests for something that the server could have added to our HTML anyway. This would be different if we could add a customer on the overview page, but because adding is done on a separate page, this data is actually static (from the viewpoint of the browser).

So can we keep using Angular, but let the server dynamically add anything to the page that it can? Luckily yes, and this is where, to me, we hit the sweet spot of SPAs: making the web application feel responsive thanks to Angular, but making it performant and limiting request thanks to ASP.NET.

Here's how.

Add a new (MVC) controller and a view. Make the controller return the view with the necessary data, taking care to add Angular attributes where necessary. Something like this:

@model IEnumerable<string>

<section id="dashboard-view" class="mainbar" data-ng-controller="customersmvc as vm">
    <h1>{{vm.title}}</h1>

    <a href="/Angular/#/customers/create">Create new customer</a>

    <p>
        The title of this view is rendered via Angular, whereas the customer names are added to
        the HTML on the server.
    </p>

    <div>
        <ul>
            @foreach (var name in Model)
            {
                <li>@name</li>
            }
        </ul>
    </div>

</section>

This page now combines Angular and ASP.NET MVC. This can be handy for data that is "dynamic" in the sense that it comes from a database, differs per user, etc but won't change once it's rendered in the browser.

For data that will change in the browser, you can still leverage Angular.

One final thing to take a look at is that ASP.NET MVC will set the Layout of the view you are loading. This is done in the _ViewStart.cshtml file. Of course, you want to keep this for pages loaded normally via ASP.NET MVC, but not for the ones loaded by Angular.

If we would keep this for the pages loaded by Angular, we would get our navigation, footer, etc. twice. You can easily avoid this by adding the following to the view:

@{Layout = null;}

So that's basically how I've combined ASP.NET MVC and Angular. Let me know if you've found a better or different way, or if you have any comments or questions.