AngularJS Components for ASP.NET MVC Developers, Part 1: Layouts and Views

When I started learning Angular it helped to associate server-side concepts I was familiar with in ASP.NET MVC to similar client-side Angular functionality. By building these associations I was able to more quickly fit the pieces together to start building real Angular applications. My hope is that by sharing these common concepts other .NET MVC developers can more efficiently transition into Angular development. In the first part of this series I’m going to discuss the basics of getting started with a simple layout page with views.

ngView / RenderBody
In MVC we generally have one (or more) layout pages per application. The rest of the .cshtml views are injected through the RenderBody() helper.

Angular has a similar concept, with HTML pages for each view injected through a div tag decorated with the ngView directive. Which view is presented at what time is determined by paths specified in your config using the $routeProvider module.

It is important to note ngView has a dependency on the ngRoute module so to gain this functionality you must include angular-route.js and declare the dependency in your app module.

RouteConfig / $routeProvider
In MVC your application routing is defined in the RouteConfig.cs file. Similarly, it is best practice to define your Angular routes in their own route-config.js file. For the sake of brevity the two are configured together below.

When a request is made with a matching URL, Angular will look for the appropriate ‘templateUrl’ property associated with the route. An AJAX call will then be made, bringing in the appropriate .html file and injecting it into ng-view. Each template will be cached so future requests will avoid going to the server. (For more advanced routing needs, ui-router, organized around states, is increasing in popularity.)

@Html.Partial / Ng-Include
Another useful strategy in MVC applications is to split up particularly complicated or large views into several partial views. This request can be accommodated quite easily in Angular with the ngInclude directive.

Utilizing ngInclude can be a powerful technique to keep complex pages clean and easy to read. Please note the URL for your HTML template is restricted to the same domain.

So there you have it, the basics of getting your layout and view set up. In the next post I will dive deeper, showing how to transition all the tricks (and more) you have learned with Razor to the client with Angular. By the end I will hopefully have convinced you to ditch server-side templating and jQuery for good! Until next time, happy coding!

View Code:GitHub/Plunker

Next ArticleAngularJS Components for ASP.NET MVC Developers, Part 2: Combining MVC and Angular Routing