Building ASP.NET Core MVC as SPA using Angular 2 and TypeScript

ASP.NET Core as MVC application is completely modular, seamlessly integrate with various JavaScript based frameworks like Angular 2, Angular 1.*, React, Knockout, JQuery etc.

In this article we will learn how to build ASP.NET Core MVC as a Single Page Application (SPA) using latest Angular 2.

When working with Angular 2 and ASP.NET Core, we should consider these points

  • Angular 2 build strategy to be used i.e. Gulp, Webpack, Rollup. The usage of Webpack is optimal approach for build mechanism.
  • Using ASP.NET Core tag helpers features also.
  • Simpler approach to include 3 party libraries
  • Working in development or production mode with ease.

These steps can be followed on Windows OS, Linux or Mac OS machines

Microsoft ASP.NET team have built up excellent infrastructure known as JavaScriptServices for building SPA based applications. At present they provide Angular 2/ React/ Knockout infrastructure. Lets get started then

Step 1 – Software prerequisites

The following software needs to be installed

  • Visual Studio Code – Light weight cross platform editor
  • Install ASP.NET and .NET Core SDK appropriate for OS
  • Latest NodeJS and NPM.
  • Install Visual Studio 2015 Update 3 (optional step). For die hard fan of VS IDE, we can use it too.

We will be using Yeoman generators for scaffolding applications. The project template for ASP.NET Core SPA needs to be installed too generator-aspnetcore-spa. Run below command to install them

Step 2 – Creating ASP.NET Core SPA app with Angular 2

Now lets create the SPA application using yeoman generator. Give a name to application and select “Angular 2” application in options. It’s command line way of creating applications

After creating ASP.NET Core MVC application, all the NPM packages are installed automatically. It takes few minutes to install all NPM packages.

Run dotnet restore from CLI to ensure all ASP.NET NuGet packages are installed

Step 3 – Understanding the project structure

The generator has created ASP.NET Core MVC application in form SPA with Angular 2, this means we already have MVC application baked with Angular 2 application. Isn’t it wonderful, lets understand project structure that is created.

asp.net core

Project Structure of MVC SPA with Angular 2

  1. ClientApp is an Angular 2 applications with modules, components, templates, Routing etc. Any further Angular 2 development code should be written here.
  2. Controllers is folder containing ASP.NET Core controllers. Both MVC and Web API controller can be written here.
  3. node_modules contains all the NPM packages installed. Package.json contains list of NPM packages needed to work with Angular 2, other technologies like bootstrap, JQuery etc. As soon as project gets created from yeoman, scripts are run from project.json
  4. Views folder contains the MVC Razor HTML files like Layout, Error etc. This shows that we are using ASP.NET Core MVC application.
  5. dist compiled folder containing Angular 2 main application, vendor files. It’s placed in wwwroot folder as its web root folder.
  6. package.json and project.json are the essential files for Angular 2 and ASP.NET Core apps. They contain all the dependencies, tooling, build information.
  7. webpack configuration files does the module bundling tasks. For Angular 2 to load, prepare bundles based on vendor files, app related files, minify when in prod are all performed using webpack configuration.

Step 4 – Two ways of running the app

This application can be run either in CLI mode or using Visual Studio Code launch settings.

Run using CLI mode

We need to run the command dotnet run from the CLI to start the application. It starts application, listens on localhost 5000 port. Open browser, navigate http://localhost:5000 to see the application in action.

When running using CLI, the application run in PROD and even Angular 2 app runs in PROD mode. However you can change it to run under Development mode too.

Run using VS Code

When you open application in VS Code, you will see following warning that required assets needs to created. Click Yes.

asp.net core

Click Yes will create .vscode folder containing two JSON files launch.json and tasks.json. They have predefined code for running application.

Opening launch.json, read through .NET Core Launch (web) configuration. It contains necessary config entries so that it can run on any OS. Also env variable ASPNETCORE_ENVIRONMENT is Development.

Just pressing the F5 the application starts running, open browser automatically, reloads on file changes and most important run in DEVELOPMENT mode.

This is how the application looks like when run using either CLI or VS Code. It’s different from the usual ASP.NET web application because this more focused for being SPA.

asp.net core

Application running in browser

What’s so special about using JavaScript services?

Personally I liked the way Angular 2 and ASP.NET Core are used together here, because

  • Developed from Microsoft ASP.NET team. Its constantly updated with framework changes.
  • Uses webpack for module bundling, soon webpack 2 will make this light weight.
  • Very simple way to tweak to run for DEV or PROD mode.
  • It also uses Angular Universal for server side rendering of Angular 2 application. This helps load apps much faster.
  • Super simple integration with third party JS libraries using Vendor packaging.
  • Inbuilt Docker support, makes deployment easy on docker containers.
  • Hot Module replacement supported when application run in development.
  • We can write Web API in the same project to access data, in turn displayed on Angular 2 apps

So far I have integrated Angular 2 in ASP.NET (MVC 5 and Core) in different ways but this is most elegant way.

Hello Readers, let me know in comments if detailed code walk through needed.

Integrating ASP.NET Core Web API and Entity Framework Core

ASP.NET Core Web API and Entity Framework Core (EF Core) are the two latest Microsoft’s offerings into Open Source world gaining momentum. We will learn to integrate them together, being cross platform technologies you are not bound to Windows for learning.

I am using Windows OS, Sql Server Express Edition and Visual Studio IDE to integrate, you can use the steps to integrate on Linux or OS X using Visual Studio Code, database like MySql, Postgresql as of now

What is Entity Framework Core (EF Core)?

Entity Framework (EF) Core is a lightweight and extensible version of the popular Entity Framework data access technology.

EF Core is an object-relational mapper (O/RM) that enables .NET developers to work with a database using .NET objects. It eliminates the need for most of the data-access code that developers usually need to write. EF Core supports many database engines. Here is the providers list

So lets started for using EF Core in ASP.Net Core Web API

Creating ASP.NET Core Web API

This is continuation of Creating ASP.NET Core WebAPI, recommend to read it to move further here. You can still create your own project too.

Adding Entity Framework Core packages

Just like ASP.NET Core is completely modular, same way EF Core is also designed to be modular i.e. the packages are split into granular with more focused functionality instead of including everything.

It has EF Core packages for various database; as we are using SQL Server Express Edition, we will add its packages. Open project.json in web api project to add EF Core package for SQL Server. You can add it using NuGet also.

Add appropriate packages for database by referring EF Core Database providers list

Create the Database Context

We are working on Contacts data model from the previous link, so lets create database context for it

DbContext class coordinates Entity Framework functionality for a given data model is the database context class. Let’s create Contexts folder (name it as you like) and in it C# class named ContactsContext, copy below code in it

Breaking down code

  1. Microsoft.EntityFrameworkCore namespace containing DbContext class to derived.
  2. ContactsContext class derives from the DbContext class to be coordinator for data model and database
  3. DbContextOptions allows us DI the configuration, provider details for DbContext to work. Lots of other functionality exists to be explored later
  4. When EF creates database, the tables has to be created too. For this C# properties that have DbSet are created as tables. At present we have only one table, if you have many tables please create DbSet properties accordingly.

Providers & Database Connection string

The database context we created above is independent of database used, in this example we are using SQL Server so we need to use appropriate provider and its database connection string to perform database related operation.

Add this code in ConfigureServices method of Startup.cs. Don’t forget to include namespace Microsoft.EntityFrameworkCore.

UseSqlServer configures the ContactsContext to connect to Microsoft SQL Server Database.

DefaultConnection is connection string for connecting to database, it should be added in appsettings.json

Tools for EF migration

At present to work with EF Core, we have command line options for operations like adding/ modifying migrations (generating database schema in C# classes), updating database.

Open project.json to add Microsoft.EntityFrameworkCore.Tools package and include EF tools for command line. Copy highlighted code into your project.json

Running EF Core commands

We included EF Core packages, created DbContext, added a provider with connection string and added tools to work command line.

For this simple example, we have two steps to follow

Init Migrations

The data models, DbSet needs to be prepared for creating SQL scripts, add init migrations command will create C# class for model snapshot i.e. database snapshot. Run the following command from project folder shown in figure

  • dotnet – executes .NET Core commands
  • ef – Entity Framework Core commands, available only if we adding EF tooling in project.json
  • add init – Initiates EF migrations for context

After this run the following command to create the Contacts database in SQL Server

Open Sql Server Express to view the Contacts database created. It’s fairly simple.

web api

Contacts DB created using EF commands

Calling ContactsContext from repository

In the previous example I have used IContactsRepository, this gets called from Web API Controllers. IContactsRepository is singleton DI injected; here is where we call use EF (Dbcontext) to call database.

We are injecting ContactsContext using DI, this was setup in Startup.cs file, using _context we can work with DbSet’s

Running WEB API and Source Code

Using either POSTMAN or Fiddler or Swagger UI, we can do testing of it. The ContactsAPI github repo contains source code. Many improvements need to be made, but its good enough to get started.

Angular Material 2 – Using in Angular 2 apps with Angular CLI

Angular Material 2 comprehensive, modern UI components that work across web, mobile and desktop. They are built on Material Design concepts. They are built with Angular 2 team.

One important point to notice even though its built by Angular 2 team, it’s not part of packages required for building Angular 2 i.e. its treated as 3rd party package to be integrated. Recommend to go through Github repo

For styling  Angular 2 apps, we can use Bootstrap, Semantic UI, its not mandatory to use material design.  Angular Material 2 components have more features apart from styling.

We will be adding these Material 2 components into Angular 2 application created using Angular CLI, we will continue from Build Angular 2 apps using CLI

Remember Angular CLI is not the only way to create Angular 2 apps & add Material 2 components

Update package.json to Angular Material 2 package

From the project root directory (same directory as package.json), run the following command to install Material 2 packages as well update package.json

Adding hammer.js to package.json

The slide-toggle and slider components have a dependency on HammerJS. You need to run this to ensure everything builds properly.

HammerJS support touch gestures to web pages

Using Material Icons and per-built theme

If you are interested in adding Material icons using md-icon in html pages, we need to include link them. Angular CLI uses Webpack to build, compose run application, it becomes much easier to add it.

Angular Material comes with per-built theme when installing packages, this can be added too. Both md-icon and pre-built theme are optional

Open src/styles.css, then add the following code in this file

Include Material Module

Angular 2 uses @NgModule for declaring components, importing modules, services as providers etc. We need to import material module to be used across the application. Refactoring to Material Module is good approach compared previous approach.

Add highlighted code into src/app/app.module.ts. This will import material components using webpack

Material components in HTML

Open src/app/app.component.html, add following code – we are using md-toolbar, md-grid-list, md-grid-tile to show planets as tiles.

Then open src/app/app.component.ts, it just loads planetslist, assign new planet member, showPlanetInfo method just assign selected planet to be shown on UI.

Clicking on the info icon, it will show planet details in bottom

Now that we have adding Material 2 package, imported them, included them in HTML, lets do ng serve to see them on web page as seen below

angular material 2

Our planets showing Material components

It’s very easy now to include Angular Material 2 components in Angular 2 application.

ASP.NET MVC 5 – Using Angular 2 with TypeScript in Visual Studio

ASP.NET MVC 5 is widely used web development framework, it’s stable, matured and most importantly its is used in production on large scale. Many folks had requested me to write how to wire up Angular 2 in MVC 5.

  • Update 31/3/17 – Github repo updated with Angular 4, TypeScript 2.1. Angular 4 is backward compatible with Angular 2 with much reduced bundle sizes.
  • Update 26/9 – Github repo updated with Angular 2 Final release version. Install TypeScript 2.0 RC

These steps can be used for new or existing MVC 5 application.

In this post I will summarize the steps needed to getting started with Angular 2 in MVC 5.

ASP.NET MVC 5 is full .NET framework web development framework, it’s different from ASP.NET Core 1.0

What we will learn?

  1. Adding package.json to MVC 5
  2. Configure to transpile TypeScript files
  3. Using gulpfile.js to move files.
  4. Add TypeScript files for bootstrapping
  5. Include systemjs.config.js to load Angular 2 modules
  6. Change HTML to load and render Angular

Step 1: Adding package.json to ASP.NET MVC 5

Assuming that you already have existing or creating new ASP.NET MVC 5. Lets add NPM configuration file known as package.json. It contains Angular 4 (works for Angular 2) & related package name to installed using NPM (Node). This is similar to package.config of NuGet.

Latest NodeJS & NPM needs to be installed.

package.json contains Angular 2 (using version 4) along with, system.js, RxJs and also some dev dependencies.

Open Command Prompt & navigate to package.json location, then run npm install this will install packages related to Angular 2 (using version 4) under node_modules folder in your folder structure.

They won’t be showing in project solution explorer, don’t worry they need not show.

Step 2: Configure to transpile TypeScript files

TypeScript(TS) would be new for most of developers, maybe these will give get started on TypeScript

In short – It’s superset of JavaScript, means everything you know about JS will be in use.

All TS files need to be transpiled or compiled to JS files so that we can run them on browser. To accomplish this we need to add “TypeScript Configuration File” called as tsconfig.json

Create a folder called “tsScripts” which contains all TS files and also configuration file. Create above tsconfig.json in this folder.

It’s fairly simple config “All TS files present in tsScripts folder will be transpiled using commonjs module to outDir (Output Directory) by keeping comments, sourceMap intact”

One of the important step is to create typings.json file, this file will create typings to ensure that TypeScript understands all Angular 2 (using version 4) modules in respect to ES5 standard.

Create JSON file with name “typings.json” & add below code then run command typings install from CMD

Step 3: Using gulpfile.js to move files

From Step 1 you got to know that all Angular 2, other packages are downloaded into node_modules in your solution folder. Now we need to move required files only like JS, sourcemaps (debugging on chrome) into our MVC 5 apps Scripts folder.

Step 2 also requires to move TS files to JavaScript file, so we use create GULP tasks which does this transpile. Also it contains CSS files movement also (which is not relevant at this point)

Create gulpfile.js in your project and copy this code

Step 4: Add TypeScript files for bootstrapping

As we are using Angular 2 with TypeScript, we need to add TS file to bootstrap the Angular app into MVC 5 app. So let’s create boot.ts file in “TsScripts” folder and copy this code.

We using ngModule to browser specifics, AppComponent.

AppComponent is starter component which we have to create it now (app.ts). Add this code below

This is template based app component which displays list.

Now create tsScripts/main.ts, this entry point where Angular 2 loads the components.

Step 5: Include systemjs.config.js to load modules

This is most important part of Angular 2 (using version 4) which loads it into the browser. There are different ways to load it but am using SystemJS here.

In the existing “Scripts” folder, create “systemjs.config.js” and copy below code

Step 6: Change csHTML to load and render Angular 2

To load Angular 2 in ASP.NET MVC 5, we need to include the script references in _Layout file and index.cshtml page.

In the Views/Home/index.cshtml you need to add “my-app” component we defined in app.TS file. This is starting point of Angular 2 application to render into browser.

Now that we are almost done, we need to run GULP tasks so that Angular 2 files, TS files are moved to appropriate folder. Open Task Runner Explorer in Visual Studio 2015 and run default task shown.

Its better to do show ALL Files in solution Explorer to see “libs“, “typings“, “app.js, boot.js, *.map” files. Includes these files and run the application to load Angular 2 in ASP.NET MVC 5.

ASP.NET MVC 5 Angular 2

Running Angular 2 in ASP.NET MVC 5

Entire source code is on my Github repo, clone or fork or download it and follow instructions to run it.

Let me know in comments if you face any issues running applications.

 

Angular Material – Using with Angular 2 and ASP.NET Core 1.0

Angular Material 2 is a set of high-quality UI components built with Angular 2 and TypeScript, following the Material Design spec. It’s built by Angular team so that it fits in Angular 2 seamlessly. Know more of it here

Why Angular Material design?

  • Internationalized and accessible so that all users can use them.
  • Browser and screen reader support
  • Code is clean and well-documented to serve as an example for Angular devs.
  • Fully tested across IE11 and current versions of Chrome, Edge, Firefox, and Safari.
  • Straightforward APIs that don’t confuse developers.

We will be integrating Angular Material UI components to ASP.NET Core 1.0 apps with Angular 2 using Visual Studio 2015 update 3. Installing TypeScript 2.0 RC is mandatory

Update October 2 – Updated to Angular Material 2 for Angular 2 final release on ASP.NET Core using webpack

Steps to add Angular Material

  1. Angular 2 & ASP.NET Core together
  2. Including Material packages in package.json
  3. Update gulpfile.js to move packages to wwwroot.
  4. Modify to systemjs.config.js to load material packages
  5. Import and use material UI components.

August 21 2016 – Updated with Angular 2 RC5, Angular Material Alpha 7 with NgModule

Step 1: Angular 2 & ASP.NET Core together

To use Angular Material UI components we need to have Angular 2 and ASP.NET Core 1.0 running together. For this follow Getting started with Angular 2 and ASP.NET Core here.

You can clone Github repo to start looking this implementation.

Step 2: Including Angular Material packages in package.json

All the Material packages can be installed using NPM, we need to add them to package.json.

All the Material 2 UI components are group into @angular/material to make it simple

Some of Material packages are button, card, checkbox, grid-list, menu etc. Read the full list of Material components.

Open the command prompt containing package.json and run below command to install Angular Material components.

The “–save” option will update your package.json to include material components.

Step 3: Import and use Material UI components using NgModule

Yes !! We are almost there, now lets import Angular 2 Material components into app.module.ts. The highlighted lines in below code are added to include all components. This is so super easy now

Step 4: Using md-icon (optional)

Material Design Icons can be added from Google API. Open clientsrc/index.html and add below code in head section

Step 5: Include UI components in template files

Open app.component.html to add UI components, at present we are showing only md-button, you can play around with other components

Running application

Now run npm start from command line & open browser, navigate localhost:3000 to see UI showing material UI components

Angular Material

 

 Check out the GITHUB repo to play around