
Introduction
In this article, let’s see how to create an ASP.NET Core CRUD Web Application with Angular 2 animation, using Template Pack, Web API, and EF 1.0.1.
Note
Kindly read my previous articles, which explain in-depth about getting started with ASP.NET Core Template Pack.
- Getting Started With ASP.NET Core Template Pack
- ASP.NET Core Angular 2 EF 1.0.1 Web API Using Template Pack
- ASP.NET Core And Angular 2 Master Detail HTML Grid Using Web API And EF 1.0.1
- Creating ASP.NET Core, Angular2 Shopping Cart Using Web API And EF 1.0.1
In this article, we will see the following.
Creating CRUD web Application using ASP.NET Core and Angular 2
- C: (Create): Insert new Student Details into the database using ASP.NET Core, EF and Web API.
- R: (Read): Select Student Details from the database using ASP.NET Core, EF and Web API.
- U: (Update): Update Student Details to the database using ASP.NET Core, EF and Web API
- D: (Delete): Delete Student Details from the database using ASP.NET Core, EF and Web API.
We will be using Web API to perform our CRUD operations. Web API has the following four methods as Get/Post/Put and Delete, where
- Get is to request for the data. (Select)
- Post is to create a data. (Insert)
- Put is to update the data. (Update)
- Delete is to delete data. (Delete)

Presenting our CRUD Application, which is more rich with simple Angular2 animations, as shown below.
- Angular2 Animation for Fade-in elements and controls.
- Angular2 Animation for move elements and controls from left.
- Angular2 Animation for move elements and controls from right.
- Angular2 Animation for move elements and controls from top.
- Angular2 Animation for move elements and controls from bottom.
- Angular2 Animation to enlarge button on click.
For creating our ASP.NET Core, Angular 2 CRUD with animation, we will be
- Creating sample database and table in SQL Server to display in our Web Application.
- Creating ASP.NET Core Angular 2 Starter Application (.NET Core), using Template Pack.
- Creating EF, DBContext Class and Model class.
- Creating WEB API for Get/Post/Put and Delete.
- Creating First Component TypeScript file to get WEB API JSON result, using Http module for Get/Post/Put and Delete method.
- Creating our first component HTML file for our animation and CRUD Web Application.
Prerequisites
Make sure, you have installed all the prerequisites in your computer. If not, then download and install all, one by one.
- First, download and install Visual Studio 2015 with Update 3 from this link.
- If you have Visual Studio 2015 and not yet updated with update 3, download and install Visual Studio 2015 Update 3 from this link.
- Download and install .NET Core 1.0.1.
- Download and install TypeScript 2.0.
- Download and install Node.js v4.0 or above. I have installed V6.9.1 (download link).
- Download ASP.NET Core Template Pack and install iy, which is a file from this link.
Code part
Step 1 - Create a database and a table
- USE MASTER
- GO
- -- 1) Check for the Database Exists .If the database is exist then drop and create new DB
- IF EXISTS (SELECT [name] FROM sys.databases WHERE [name] = 'StudentsDB' )
- DROP DATABASE StudentsDB
- GO
- CREATE DATABASE StudentsDB
- GO
- USE StudentsDB
- GO
- -- 1) //////////// StudentMasters
- IF EXISTS ( SELECT [name] FROM sys.tables WHERE [name] = 'StudentMasters' )
- DROP TABLE StudentMasters
- GO
- CREATE TABLE [dbo].[StudentMasters](
- [StdID] INT IDENTITY PRIMARY KEY,
- [StdName] [varchar](100) NOT NULL,
- [Email] [varchar](100) NOT NULL,
- [Phone] [varchar](20) NOT NULL,
- [Address] [varchar](200) NOT NULL
- )
- -- insert sample data to Student Master table
- INSERT INTO [StudentMasters] ([StdName],[Email],[Phone],[Address])
- VALUES ('Shanu','[email protected]','01030550007','Madurai,India')
- INSERT INTO [StudentMasters] ([StdName],[Email],[Phone],[Address])
- VALUES ('Afraz','[email protected]','01030550006','Madurai,India')
- INSERT INTO [StudentMasters] ([StdName],[Email],[Phone],[Address])
- VALUES ('Afreen','[email protected]','01030550005','Madurai,India')
- select * from [StudentMasters]
Step 2 - Create ASP.NET Core Angular 2 Application

After creating ASP.NET Core Angular 2 Application, wait for few seconds. You will see that all the dependencies are automatically restored.
What is new in ASP.NET Core Template Pack solution?

WWWroot
We can see that all the CSS,JS files are added in “dist” folder .”main-client.js” file is an important file as all the Angular 2 results will be compiled and loaded from this “JS” file to our HTML file.

ClientApp folder
We can see a new folder ClientApp inside our project solution. This folder contains all Angular 2 related Applications like modules, components etc. We can add all our Angular 2 related modules, components, template HTML files, which are all under this folder. We can see in the details about how to create our own Angular 2 Application here as shown below in our article.
In Components folder, under app folder, we can see many subfolders like app. counter, fetchdata, home, and navmenu. By default, this sample application has been created and when we run our application, we can see all the sample results.

When we run the application, we can see that the left side has navigation and the right side contains the data. All Angular 2 samples will be loaded from the above folder.

Controllers folder
This is our MVC Controller folder. We can create both MVC and Web API Controller in this folder.
View folder
This is our MVC View folder.
Other Important files
We can also see other important ASP.NET Core filessuch as:
project.json
ASP.NET Core dependency list can be found in this file. We will be adding our Entity Framework in the dependency section of this file.
package.json
This is another important file as all Angular 2 related dependency lists will be added here by default. All Angular 2 related dependencies have been added in ASP.NET Core Template Pack.
appsettings.json
We can add our database connection string in this appsetting.json file. We will be using all this in our project to create, build and run our Angular 2 with ASP.NET Core Template Pack, WEB API and EF 1.0.1.
Step 3 - Creating Entity Freamework
Add Entity Framework Packages
To add our Entity Framework Packages in our ASP.NET Core Application, open Project.JSON File and in dependencies, add the line given below to it.
Note
Here, we have used EF version 1.0.1.
- "Microsoft.EntityFrameworkCore.SqlServer": "1.0.1","Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"

When we save the project.json file, we can see the reference has been restored.
After a few seconds, we can see Entity Framework package has been restored and all references have been added.
Adding connection string
To add the connection string with our SQL connection, open the “appsettings.json” file .Yes this is a JSON file and this file looks as shown below.

In this appsettings.json file, I have added the connection string
- "ConnectionStrings": {
- "DefaultConnection": "Server=YOURDBSERVER;Database=StudentsDB;user id=SQLID;password=SQLPWD;Trusted_Connection=True;MultipleActiveResultSets=true;"
- },
Note- Change SQL connection string, as per your local connection.

Next step is to create a folder named Data to create our model and DBContext class.
Creating Model class for Student
We can create a model by adding a new class file in our Data folder. Right Click Data folder and click Add>Click Class. Enter the class name as StudentMasters and click Add.

Now, in this class, we first create a property variable, add student. We will be using this in our WEB API controller.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using System.ComponentModel.DataAnnotations;
- namespace Angular2ASPCORE.Data
- {
- public class StudentMasters
- {
- [Key]
- public int StdID { get; set; }
- [Required]
- [Display(Name = "Name")]
- public string StdName { get; set; }
- [Required]
- [Display(Name = "Email")]
- public string Email { get; set; }
- [Required]
- [Display(Name = "Phone")]
- public string Phone { get; set; }
- public string Address { get; set; }
- }
- }
Creating Database Context
DBContext is Entity Framework class to establish a connection to the database
We can create a DBContext class by adding a new class file in our Data folder. Right click Data folder and click Add>Click Class. Enter the class name as StudentContext and click Add.

In this class, we inherit DbContext and created Dbset for our students table.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using Microsoft.EntityFrameworkCore;
- namespace Angular2ASPCORE.Data
- {
- public class studentContext:DbContext
- {
- public studentContext(DbContextOptions<studentContext> options)
- :base(options) { }
- public studentContext() { }
- public DbSet<StudentMasters> StudentMasters { get; set; }
- }
- }
Startup.CS
Now, we need to add our database connection string and provider as SQL SERVER. To add this, we add the code given below in Startup.cs file under ConfigureServices method.
- // Add Entity framework .
- services.AddDbContext<studentContext>(options =>options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
Step 4 - Creating Web API for CRUD operation
To create our WEB API Controller, right click Controllers folder. Click Add and click New Item.
Click ASP.NET in right side. Click Web API Controller class. Enter the name as “StudentMastersAPI.cs” and click Add.

As we all know, Web API is a simple and easy way to build HTTP Services for the Browsers and Mobiles.
Web API has four methods given below as Get/Post/Put and Delete.
- Get is to request for the data. (Select)
- Post is to create a data. (Insert)
- Put is to update the data.
- Delete is to delete data.
Get Method(Select Operation)
Get Method is to request single item or list of items from our selected database. Here, we will get all student information from StudentMasters table.
- [HttpGet]
- [Route("Student")]
- public IEnumerable<StudentMasters> GetStudentMasters()
- {
- return _context.StudentMasters;
- }
Post Method (Insert Operation)
Post Method will be used to insert the data to our database. In Post Method, we will also check if StudentID is already created and return the message. We will pass all Student Master Column parameters to be inserted in to the Student Master table.
- // POST: api/StudentMastersAPI
- [HttpPost]
- public async Task<IActionResult> PostStudentMasters([FromBody] StudentMasters studentMasters)
- {
- if (!ModelState.IsValid)
- {
- return BadRequest(ModelState);
- }
- _context.StudentMasters.Add(studentMasters);
- try
- {
- await _context.SaveChangesAsync();
- }
- catch (DbUpdateException)
- {
- if (StudentMastersExists(studentMasters.StdID))
- {
- return new StatusCodeResult(StatusCodes.Status409Conflict);
- }
- else
- {
- throw;
- }
- }
- return CreatedAtAction("GetStudentMasters", new { id = studentMasters.StdID }, studentMasters);
- }
- private bool StudentMastersExists(int id)
- {
- return _context.StudentMasters.Any(e => e.StdID == id);
- }
Put Method (Update Operation)
Put Method will be used to update the selected student data to our database. In Put Method, we will pass StudentID along with all other parameters for update.We pass the StudentID to update the StudentMaster Table by StudentID.
- // PUT: api/StudentMastersAPI/5
- [HttpPut("{id}")]
- public async Task<IActionResult> PutStudentMasters([FromRoute] int id, [FromBody] StudentMasters studentMasters)
- {
- if (!ModelState.IsValid)
- {
- return BadRequest(ModelState);
- }
- if (id != studentMasters.StdID)
- {
- return BadRequest();
- }
- _context.Entry(studentMasters).State = EntityState.Modified;
- try
- {
- await _context.SaveChangesAsync();
- }
- catch (DbUpdateConcurrencyException)
- {
- if (!StudentMastersExists(id))
- {
- return NotFound();
- }
- else
- {
- throw;
- }
- }
- return NoContent();
- }
Delete Method (Delete Operation)
Delete Method will be used to delete the selected student data from our database. In Delete Method, we will pass StudentID to delete the record.
- // DELETE: api/StudentMastersAPI/5
- [HttpDelete("{id}")]
- public async Task<IActionResult> DeleteStudentMasters([FromRoute] int id)
- {
- if (!ModelState.IsValid)
- {
- return BadRequest(ModelState);
- }
- StudentMasters studentMasters = await _context.StudentMasters.SingleOrDefaultAsync(m => m.StdID == id);
- if (studentMasters == null)
- {
- return NotFound();
- }
- _context.StudentMasters.Remove(studentMasters);
- await _context.SaveChangesAsync();
- return Ok(studentMasters);
- }
To test Get Method, we can run our project and copy the GET method API path. Here, we can see our API path to get api/StudentMastersAPI/Student
Run the program and paste API path to test our output.

Working with Angular2
We create all Angular2 related Apps, Modules, Services, Components and HTML templates under ClientApp/App folder.
We create “students” folder under app folder to create our TypeScript and HTML file to display Student details.

Step 5 - Working with Angular 2 animation

Angular animations are all built on top of the standard Web Animations API. Kindly check this reference link, which explains more detail about Angular2 animations at https://angular.io/docs/ts/latest/guide/animations.html
Adding Animation in Web Applications will give a more rich look for our Website. Here, in this application, we will be using Angular2 animation for Fade-in Enlarge controls on click event and move the elements or controls from left, right, top and bottom.
Angular2 animation in Home Component
Here, we will be adding our animation in our home page. For this, we edit the Home Component to create our Angular2 animation.
Import part
For using the Angular2 animation, we need to first import “trigger, state, style, transition, animate”.
Our import will look as shown below.
- import {Component, Input, trigger, state, style, transition, animate, keyframes} from '@angular/core';
Component part
In component, we need to add animations: [] to perform our animation with triggers.
The trigger is used to connect Component with our HTML Template. For example, it allows you, on creating a simple animation, to change the color and resize the button on click event.
For this, we need to first create a trigger with the name “moveBottom”. We will be using this trigger name in our HTML element or control to move from bottom. In this animation, we have used transition ('void => *' which means this animation will be performed during the page load. We have set the amination time for '1s' and in style, we set the 'translateY(-200px), which means we initially set the button location to bottom -200 from the actual location of the button. When the page loads the button will start from -200 Y-axis place and move up to the actual button location that is 'translateY(0)'
- trigger('moveBottom', [
- transition('void => *', [
- animate('1s', keyframes([
- style({ opacity: 0, transform: 'translateY(-200px)', offset: 0 }),
- style({ opacity: 1, transform: 'translateY(25px)', offset: .75 }),
- style({ opacity: 1, transform: 'translateY(0)', offset: 1 }),
- ]))
- ])
- ])
In HTML template, we will be using this trigger name with @ symbol to perform the animation, as shown below. Here, we have added the animation for div tag.
- <div [@moveBottom]= ‘moveBottom’>
- ASP.NET Angular2
- </div>
It is similar to Bottom. We do the rest of animations for left, right, top and Fade-In. Here is the complete code for Home animation component.
- import { Component, Input, trigger, state, style, transition, animate, keyframes } from '@angular/core';
- @Component({
- selector: 'home',
- animations: [
- trigger('moveBottom', [
- transition('void => *', [
- animate('1s', keyframes([
- style({ opacity: 0, transform: 'translateY(-200px)', offset: 0 }),
- style({ opacity: 1, transform: 'translateY(25px)', offset: .75 }),
- style({ opacity: 1, transform: 'translateY(0)', offset: 1 }),
- ]))
- ])
- ]),
- trigger('moveTop', [
- transition('void => *', [
- animate('1s', keyframes([
- style({ opacity: 0, transform: 'translateY(+400px)', offset: 0 }),
- style({ opacity: 1, transform: 'translateY(25px)', offset: .75 }),
- style({ opacity: 1, transform: 'translateY(0)', offset: 1 }),
- ]))
- ])
- ]),
- trigger('moveRight', [
- transition('void => *', [
- animate('1s', keyframes([
- style({ opacity: 0, transform: 'translateX(-400px)', offset: 0 }),
- style({ opacity: 1, transform: 'translateX(25px)', offset: .75 }),
- style({ opacity: 1, transform: 'translateX(0)', offset: 1 }),
- ]))
- ])
- ]),
- trigger('movelLeft', [
- transition('void => *', [
- animate('4s', keyframes([
- style({ opacity: 0, transform: 'translateX(+800px)', offset: 0 }),
- style({ opacity: 1, transform: 'translateX(150px)', offset: .75 }),
- style({ opacity: 1, transform: 'translateX(0)', offset: 1 }),
- ]))
- ])
- ]),
- trigger('fadeIn', [
- transition('void => *', [
- animate('3s', keyframes([
- style({ opacity: 0, transform: 'translateX(0)', offset: 0 }),
- style({ opacity: 1, transform: 'translateX(0)', offset: 1 }),
- ]))
- ])
- ])
- ],
- template: require('./home.component.html')
- })
- export class HomeComponent {
- myName: string = "Shanu";
- }
Here is the complete code for Home HTML template.


Andrew SmithPosted Mar 21, 2017, 8:50 AM
You forgot to mention that you need to put an "Images" folder in students with edit.gif and delete.gif. Otherwise very nice article.
Ravi KandelPosted Mar 8, 2017, 8:38 AM
Awesome Thanks for sharing
Anu VPosted Mar 7, 2017, 6:52 AM
Nice article.. thanks for sharing..