SHASHANGKA SHEKHAR'S BLOG

Author, TechWriter

ASP.Net Core2.0 & Angular6-SPA

Hits: 177

In this post, we are going to explore how a Single Page Application (SPA) sample can be put together using ASP.Net Core & Angular from scratch.

Table of Contents:

  • Introduction
  • Work Plan
  • Development Environment
  • Core Description
  • Summary
  • Downloads 

Introduction:

We are going to use Angular6, TypeScript in frontend and backend using ASP.NET Core WebAPI with Entity Framework Core database operations.

Work Plan:

  • Create New ASP.Net Core Project
  • Configure Newly Created Project
    • Serve Static Page
  • Install Node Packages
  • Manage Installed Packages
  • Create Frontend Application
    • HTML Templating
    • Folder Structure
    • Angular Dependencies
    • TypeScript Configuration
    • Root Component
    • Root Module
    • Bootstrapping Clientapp
  • Creating Database
  • Install Entity Framework Core
  • Scaffolding MSSQL Database
  • Configure Middleware
  • Creating ASP.Net Core WebAPI
  • Creating Client Services
  • Perform CRUD Operation
  • Test in Browser

Development Environment:

Following are prerequisites to develop our SPA sample.

  • Visual Studio 2017
  • NET Core 2.0 or later
  • NodeJS and NPM

Visual Studio 2017: If you already have a copy of Visual Studio 2017 installed don’t worry otherwise Download Visual Studio Community 2017 for free.

.NET Core Downloads: Install the .NET Core SDK (Software Development Kit) 2.0 or later.

NodeJS and NPM: Install latest NodeJS and NPM

Make sure the environment is ready before stepping into.

Create ASP.Net Core Project:

Let’s create a new project with Visual Studio 2017 > File > New > Project

Choose empty template click > OK.

Here’s our new ASP.Net Core empty project with initial components.

Configure ASP.Net Core Project:

In this sample we are going to serve index.heml page as our main page from app root folder, to serve the page we need to configure in Startup.cs file. Here is the code snippet which is going to serve the page.

Middleware to Handle Client Side Routes Fallback:

To avoid 404 error while reload the page in AngularJS SPA app we need to add middleware to handle client side route fallback. Below code snippet will take care of that. Here’s the original post: https://code.msdn.microsoft.com/How-to-fix-the-routing-225ac90f

Get more details on middleware here: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?tabs=aspnetcore2x

Install Node Packages:

Let’s add frontend packages to our application. We need to add npm configuration file named package.json.

To do that right click the project then Goto > Add > New Item. From the new item add window choose npm Configuration File.

Here’s our list of frontend package dependencies.

After installation all packages let’s transfer the required libraries from node_modules folder to “wwwroot/lib” for calling it to the main html page.

Manage Installed Packages:

We need to add a task runner like gulp file, then copy below code snippet and paste it to the newly added file.

Right click on gulpfile.js then go to “Task Runner Explorer”.

From the new window refresh the task then right click on task to run it like below screen.

As we can see our required libraries are loaded in “wwwroot/lib” folder.

Frontend Application

HTML Templating: In this section we are going to add basic bootstrap template to our main html page.

Folder Structure:

Below is our folder structure for the sample app. As we can see ‘clientapp’ is the root folder that consist of entry point file & root module. Root module has app component where other components are relate to root module through app component.

Angular Dependencies: To enable ES6 new feature we need to resolve below dependencies.

SystemJS Import : Here’s our application is loading to the browser by System.import() function.

Before importing module we need to configure SystemJS by using System.config() function we are going to define which package/file to load.

SystemJS Config : systemjs.config.js

TypeScript Configuration:

We need to convert our typescript code to JavaScript for browser support by configuring TypeScript compiler. Below code snippet is for tsconfig.json file.

Configure Typescript : tsconfig.json

Root Component: 

Every application has a root component which has two part annotation and definition. It has selector to match with main html page to render.

Root Module:

This is where our application components are defines, a module may have multiple component. Every application has a root module.

Bootstrapping Clientapp:

Let’s create a main entry file, name it main.ts. Copy below code snippet paste it to newly created typescript file.

In this point our application is bootstraps and launch the root module in browser. Here’s how we are bootstrapping our application in index.html page.

Main Html Page:

Let’s build and run the application.

Our application is running, as we can see upper screen is appearing with welcome message. Next we will create form then submit & validate after that we are going to perform CRUD operations with SQL Database.

Creating Database:

Let’s Create a Database in MSSQL Server. Here is the table where we are storing data. Run below script in query window to create new database.

Creating Table:

Install Entity Framework Core:

Entity Framework (EF) Core is data access technology which is targeted for cross-platform. Let’s right click on project then GoTo > Tools > NuGet Package Manager > Package Manager Console install below packages one by one.

  • Install-Package Microsoft.EntityFrameworkCore.SqlServer
  • Install-Package Microsoft.EntityFrameworkCore.SqlServer.Design
  • Install-Package Microsoft.EntityFrameworkCore.Tools.DotNet

EntityFrameworkCore.SqlServer: Database Provider, that allows Entity Framework Core to be used with Microsoft SQL Server.

EntityFrameworkCore.SqlServer.Design: Design-time, that allows Entity Framework Core functionality (EF Core Migration) to be used with Microsoft SQL Server.

EntityFrameworkCore.Tools: Command line tool for EF Core that Includes Commands

Scaffolding MSSQL Database:

We are going to generate EF models from existing database using reverse engineering using command in Package Manager Console.

Command:

For Package Manager Console:

  • Scaffold-DbContext
  • Add-Migration
  • Update-Database

For Command Window

  • dotnet ef dbcontext scaffold

As we can see from solution explorer models folder is created with Context & Entities.

Now open the DbContext file then add a constructor to pass configuration like connectionstring into the DbContext.

Configure Middleware:

Register DbContext: In Startup.cs let’s add our DbContext as service to enable database connection.

Creating ASP.Net Core WebAPI:

Here’s our ASP.Net Core WebAPI Controller using specific RoutePrefix attribute globally. With this api controller class we are performing database operation using Entity Framework DbContext.

All right, our WebAPI is ready to interact with database. Our next step is to prepare client model, component and services to interact with WebAPI’s.

Perform CRUD Operation:

Let’s get started with form design. There are two strategy of angular6 form, in this sample we have used Model-driven form.

  1. Template-driven
  2. Model-driven

UI: user.html

Let’s create a typescript model class, then use it in another component by importing like

Typescript Model : UserModel

Below is our UserComponent that is interacting with UI, validating form then sending/receiving data from service component.

Imports the Component function from Angular6 library, use of “export” that mean app component class can be imported from other component.

Component : UserComponent

Below is service component which will get call for each operation performed by UserComponent.

In our UserService we have Http service [Get, Post, Put, Delete] that connect with WebAPI to perform Create, Read, Update & Delete operations.

Http Client Services : UserService  

Test in Browser:

Now it’s time to build & run the application. Let’s try to perform the CRUD operation using the system. As we can see from below screenshot data are loading in user page from database.

Summary:

In this sample we have combine ASP.Net Core & Angular to create the sample SPA app without any CLI, learn how to start with an empty ASP.Net Core application to serve static html page.

We also have deep dive into latest frontend technology like Angular6 from scratch to build a single page application. Have a short overview on Angular6 dependencies & also have ideas of module, components. Then we have perform some database operation using our sample application. Hope this will help.

Downloads:

I’ve uploaded the full source code to download/clone @github, Thanks 🙂

Post a comment