Click here to Skip to main content
15,615,280 members
Articles / Web Development
Posted 5 Aug 2016


36 bookmarked

ASP.NET Core1.0 Insert/Select to Database Using Angular2 and WEB API

Rate me:
Please Sign up or sign in to vote.
4.94/5 (27 votes)
24 Aug 2016CPOL11 min read
In this article you will learn about Insert/Select to database using Angular2 and WEB API in ASP.NET Core1.0.


Image 1

In our previous article,

we have seen in detail about ASP.NET Core 1.0, Angular2 and WEB API to display the data.

In this article we will see in detail about using ASP.NET Core 1.0 with Angular2 to Insert and Select Student Details to SQL Server Database using WEB API. 

In this article we will see in detail how to,

  • Create our ASP.NET Core 1.0 RC2 Web Application.
  • Create Model to add Student details.
  • Create WEB API Controller using Entity framework to Select and Insert data to database.
  • How to add TypeScript JSON Configuration File
  • How to add grunt package using NPM configuration file
  • How to configure Grunt File.
  • Adding Dependencies to install Angular2 and all other files
  • How to create our Angular2 App, boot using Type Script file.
  • Using HTTP Get/Post to Insert and select data from Angular2 to WEB API to insert in DB.
  • Creating HTML File
  • How to Run the Grunt file using Visual Studio Task Runner Explorer
  • How to Run and view our Sample.

Reference website :


  • Visual Studio 2015: You can download it from here.
  • ASP.NET Core 1.0 RC2: download link,link2.

Using the code

We will be using our SQL Server database for our WEB API. First we create a database named  StudentsDB and a table as StudentMaster. Here is the SQL script to create Database table and sample record insert query in our table. Run the below query in your local SQL server to create Database and Table to be used in out project.

-- 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' ) 
USE StudentsDB 
-- 1) //////////// StudentMasters 
IF EXISTS ( SELECT [name] FROM sys.tables WHERE [name] = 'StudentMasters' ) 
DROP TABLE StudentMasters 
CREATE TABLE [dbo].[StudentMasters]( 
        [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','','01030550007','Madurai,India') 
INSERT INTO [StudentMasters]   ([StdName],[Email],[Phone],[Address]) 
     VALUES ('Afraz','','01030550006','Madurai,India') 
INSERT INTO [StudentMasters]   ([StdName],[Email],[Phone],[Address]) 
     VALUES ('Afreen','','01030550005','Madurai,India') 
     select * from [StudentMasters]

Step 1: Create our ASP.NET Core 1.0 Web Application.

After installed both Visual Studio 2015 and ASP.NET Core 1.0 RC2. Click Start, then Programs and select Visual Studio 2015 - Click Visual Studio 2015. Click New, then Project, select Web and select ASP.NET Core Web Application. Enter your Project Name and click OK.

Image 2

Next select Web Application. If you are not hosting in Cloud then you can uncheck the Host in the Cloud at the bottom right corner. Click OK

Image 3

Now we have

Image 4

Database Connection String:

Now we need to change the local connection string from ASP.Net 5 project with our SQL Server connection.

Note: In ASP.NET Core 1.0 we need to use “appsettings.json” file instead of web.config.We can find the “appsettings.json” file from our ASP.NET Core 1.0 solution.

Image 5

To change the default connection string with our SQL connection open the “appsettings.json” file .Yes this is JSON file and this file looks like below Image by default.

Image 6

Now the default connectionstring will be something like this

"ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-Core1.0Angular2CRUDInsert-599f2ca4-119a-4fd5-a2a4-e58fb4b2e5be;Trusted_Connection=True;MultipleActiveResultSets=true"
Now we change this to our SQL Connection like below,
"ConnectionStrings": {
    "DefaultConnection": "Server=SQLSERVERNAME;Database=StudentsDB;user id=SQLID;password=SQLPWD;Trusted_Connection=True;MultipleActiveResultSets=true;"

Step 2: Creating MVC Model to return student list

We can create a model by adding a new class file in our Model Folder.
Image 7

Right click the Models folder and click new Item .Select Class and enter your class name as “StudentMasters.cs”

Image 8

Now add in this class we first create property variable,add student.We will be using this in our WEB API controller.

using System.ComponentModel.DataAnnotations;
namespace WebApplicationTestSample.Models
    public class StudentMasters
        public int StdID { get; set; }

        [Display(Name = "Name")]
        public string StdName { get; set; }

        [Display(Name = "Email")]
        public string Email { get; set; }

        [Display(Name = "Phone")]
        public string Phone { get; set; }

        public string Address { get; set; }


Step 3: Creating WEB API Controller

We can create a controller by adding a new Empty API Controller in our Controller Folder.

Image 9

Right click the Controller folder and Add Controller .Select API Controller with action, using Entity Framework and click Add

Image 10

Select the Model class as  StudentMasters.

Image 11

After selecting the Model Class select the Data Context Class. Here we are selecting the default ApplicationDbContext. Note we have set the default connection string to our SQL Server database Connection.Next give our WEB API controller name as StudentMastersAPI.

Image 12

We can see that our WEB API Controller has been created now and also the controller will contain default Select (HttpGet) and Insert method as (HttpPost). We will be using this get and post method In our Angular2 to select and insert data to database .

Image 13

To test it we can run our project and copy the get method api path here we can see our API path for get is api/StudentMastersAPI/

Run the program and paste the above API path to test our output.

Image 14

Step 4: How to add TypeScript JSON Configuration File

The TypeScript JSON file will file specifies the root files and the compiler options required to compile the project .To know more about TypeScript JSON Configuration kindly visit this sites ,

To create the TypeScript JSON file right click on you Project and Click Add new Item.

Image 15

Select TypeScript JSCON Configuration File and Click ok. The File will be look like below image.

Image 16

Now copy the below code and replace with your config file.

"compilerOptions": {
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "module": "commonjs",
    "moduleResolution": "node",
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "target": "es5",
 "sourceMap": true

Image 17

Step 5: How to add grunt package using NPM configuration file

Now we need to add a NPM Configuration File for adding a grunt package to run our java scripts.

As we have created as a Web Application the NPM Configuration File will be located in our project.

By default we can’t view our NPM Configuration File. The NPM Configuration File will be in the name of “package.JSON” . TO view that from the Solution Explorer click on “Show All Files”

Now open the “package.JSON” file .Now first we need to change the name to our project Solution name and add our grunt package .we can see the code here below the image.

Image 18

Here we have changed the name as our Solution name and also added the grunt package.

  "name": "test",
  "version": "0.0.0",
  "private": true,
"devDependencies": {
    "grunt": "1.0.1",
    "grunt-contrib-copy": "1.0.0",
    "grunt-contrib-uglify": "1.0.1",
    "grunt-contrib-watch": "1.0.0",
    "grunt-ts": "5.5.1",
    "gulp": "3.8.11",
    "gulp-concat": "2.5.2",
    "gulp-cssmin": "0.1.7",
    "gulp-uglify": "1.2.0",
    "rimraf": "2.2.8"

Now save the package.json file and you should be able to see a grunt package under Dependencies/ npm Folder will be first Resorted and then installed.

Restoring :

Image 19

All Installed:

Image 20

Step 6: Configure Grunt File.

Grunt is used to build all our client side resources like JavaScript for our project.

First step is to add a Grunt file to our project. Right click our project and Select Grunt Configuration File and click Add.

Image 21

After creating the file now s we need to edit this file to add load plugins, configure plugins and define tasks

Here in our Grunt file we have first load plugins which we have added in our npm. Using loadNpmTask here we load 'grunt-contrib-copy ,'grunt-contrib-uglify' , 'grunt-contrib-watch'

Image 22

Next we configure the grunt add the app.js file in our wwwroot folder. All our Script files from Scripts folder result will be added in this app.js file. Next we need to copy all the Script file from 'node_modules/ to our local js Folder.

The watch plugin will be used to check for any changes on JavaScript file and update it app.js with all new changes.

This file in the main entry point for defining grunt tasks and using grunt plugins.
Click here to learn more.
module.exports = function (grunt) {
                src: ['Scripts/app/boot.ts', 'Scripts/app/**/*.ts'],
                outDir: 'wwwroot/app',
                tsconfig: './tsconfig.json'
                files: [{
                    expand: true,
                    cwd: 'wwwroot/app',
                    src: ['**/*.js'],
                    dest: 'wwwroot/app'
                sourceMap: true
        // Copy all JS files from external libraries and required NPM packages to wwwroot/js  
        copy: {
            main: {
                         expand: true,
                         flatten: true,
                         src: ['Scripts/js/**/*.js', 'node_modules/es6-shim/es6-shim.min.js', 'node_modules/systemjs/dist/system-polyfills.js', 'node_modules/angular2/bundles/angular2-polyfills.js', 'node_modules/systemjs/dist/system.src.js', 'node_modules/rxjs/bundles/Rx.js', 'node_modules/angular2/bundles/'],
                         dest: 'wwwroot/js/',
                         filter: 'isFile'
        // Watch specified files and define what to do upon file changes  
        watch: {
            scripts: {
                files: ['Scripts/**/*.js'],
                tasks: ['ts', 'uglify', 'copy']
    // Define the default task so it will launch all other tasks  
    grunt.registerTask('default', ['ts', 'uglify', 'copy', 'watch']);

Step 7: Adding Dependencies to install Angular2 and all other files

We are using NPM to install our Angular2 in our web application. Open our Package.JSON file and the below dependencies.

"dependencies": {
    "@angular/http": "2.0.0-rc.1",
    "angular2": "^2.0.0-beta.8",
    "angular2-jwt": "0.1.16",
    "angular2-meteor": "0.5.5",
    "cors": "2.7.1",
    "systemjs": "0.19.22",
    "es6-promise": "^3.0.2",
    "es6-shim": "^0.33.3",
    "reflect-metadata": "0.1.2",
    "rxjs": "5.0.0-beta.2",
    "tsd": "^0.6.5",
    "zone.js": "0.5.15"

The edited Package.json file will be look like below image.

Image 23

Save the file and wait for few second to complete all decencies installed.

Image 24

Step 8 How to create our Angular2 App, boot using Type Script file.

Now it’s time to create our Angular2 application. First create a Folder named Scripts. Right click our project and click add new Folder and name the folder name as “Scripts”. Now we will create our TypeScript files inside this Scripts folder.

To work with Angular2 we need to create 2 important TypeScript file.

  1. Component File where we write our Angular coding.
  2. Boot file: To run our component app .

Creating App TypeScript file:

Right Click on Scripts folder and click on add new Item. Select TypeScript File and name the file as App.ts and click Add.

Image 25

In App.ts file we has three parts first is the

  1. import part
  2. Next is component part
  3. Next we have is the class for writing our business logics.

Here we can see a simple basic one way binding example to display the welcome message in side h1 tag.Here.

1. import part : first we import angular2 files to be used in our component here we import http for using http client in our Angular2 component and importing NgFor for using the looping and bind all the student details array value one by one,and also we are importing one more typescript export class name StudentMasters from the model file.

import { Component, Injectable, Inject} from 'angular2/core';
import { NgIf, NgFor } from 'angular2/common';
import {Http, Response, HTTP_PROVIDERS, Headers, RequestOptions} from 'angular2/http';
import { StudentMasters } from './model';
import {Observable} from 'rxjs/Observable';
import 'rxjs/Rx';

2.Next is component part :

In component we have selector, directives and template. Selector is to give name for this app and in our html file we use this selector name to display in our html page.

In template we write our code. IN template first we create a form to insert Student details to database using the http post method. In Button click we call the addStudentsDetails()  method to insert student details. After insert we call the getData() method to bind the updated result.

To display the StudentMaster details we are using ngFOR inside html the method we have used http get function to load data from WEB API and to display in our html page. We have made all the design inside the template. There is also another method as we can create a html file and add all the design in that html page and in template we can give the html file name.

    selector: "my-app",
    directives: [NgFor],
    template: `     
<table style="background-color:#FFFFFF; border: dashed 3px #6D7B8D; padding :5px;width :99%;table-layout:fixed;" cellpadding="2" cellspacing="2">
                    <tr style="height: 30px; background-color:#336699 ; color:#FFFFFF ;border: solid 1px #659EC7;">
                      <h2>Insert Student Details : </h2>
 <table style="color:#9F000F;font-size:large" cellpadding="4" cellspacing="6">
     <td><b>Students ID: </b> </td>
      <input  [(ngModel)]="students.StdID" value="0" style="background-color:tan" readonly>
  <td><b>Students Name: </b> </td>
    <input  [(ngModel)]="students.StdName" >
     <td><b>Email: </b> </td>
      <input  [(ngModel)]="students.Email" >
  <td><b>Phone: </b> </td>
    <input  [(ngModel)]="students.Phone" >
     <td><b>Address: </b> </td>
     <input  [(ngModel)]="students.Address" >
  <td colspan="2">
<button (click)=addStudentsDetails() style="background-color:#334668;color:#FFFFFF;font-size:large;width:200px;

<tr><td>&nbsp; </td></tr>

 <table style="background-color:#FFFFFF; border solid 2px #6D7B8D; padding 5px;width 99%;table-layout:fixed;" cellpadding="2" cellspacing="2">

                                <tr style="height: 30px; background-color:#336699 ; color:#FFFFFF ;border: solid 1px #659EC7;">
                                    <td width="100" align="center">Student ID</td>
                                    <td width="240" align="center">Student Name</td>
                                    <td width="240" align="center">Email</td>
                                    <td width="120" align="center">Phone</td>
                                    <td width="340" align="center">Address</td>

                                <tbody *ngFor="let std of student">

                                        <td align="center" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">
                                            <span style="color:#9F000F">{{std.StdID}}</span>

                                        <td align="left" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">
                                            <span style="color:#9F000F">{{std.StdName}}</span>

                                        <td align="left" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">
                                            <span style="color:#9F000F">{{std.Email}}</span>

                                        <td align="center" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">
                                            <span style="color:#9F000F">{{std.Phone}}</span>

                                        <td align="left" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">
                                            <span style="color:#9F000F">{{std.Address}}</span>


3. Export Class :

This is the main class where we do all our business logic and variable declaration to be used for in our component this class we have created a method named getData() and in this method we get the API method result and bind the result to the student array. In button click we call the addStudentsDetails() method to insert the data to database using http post method.

 export class AppComponent {
    student: Array<StudentMasters> = []; 
    students = {};
    myName: string;  
    constructor(@Inject(Http) public http: Http) {
        this.myName = "Shanu";      

    getData() {         
            .map((responseData) => {
                return responseData.json();
            .map((student: Array<any>) => {
                let result: Array<StudentMasters> = [];
                if (student) {
                    student.forEach((student) => {
                        result.push(new StudentMasters(student.StdID, student.StdName,
                            student.Email, student.Phone, student.Address));
                return result;
            .subscribe(res => this.student = res);

    addStudentsDetails() {     
        var headers = new Headers();
        headers.append('Content-Type', 'application/json; charset=utf-8');'api/StudentMastersAPI', JSON.stringify(this.students), { headers: headers }).subscribe();
        alert("Student Detail Inserted");

Next we need to add the boot.ts file to run our app.

Creating boot TypeScript file:

Right Click on Scripts folder and click on add new Item. Select TypeScript File and name the file as boot.ts and click Add.

Image 26

In boot.ts file we add the below code. Here first we import bootsrap file to load and run our app file and also we import our app component. Note to import our app we need to give the same class name which was given in our app typescript file and give our app path in from  as ’./app’ .Next we run our app by adding the app name in bootstrap as bootstrap(myAppComponent);.

///<reference path="../node_modules/angular2/typings/browser.d.ts" />  

import {bootstrap} from 'angular2/platform/browser'
import {ROUTER_PROVIDERS} from "angular2/router";
import {HTTP_PROVIDERS, HTTP_BINDINGS} from "angular2/http";
import {AppComponent} from './app'

bootstrap(AppComponent, [HTTP_BINDINGS, HTTP_PROVIDERS]);

Creating model TypeScript file:

Right Click on Scripts folder and click on add new Item. Select TypeScript File and name the file as model.ts and click Add.

We use this model typescript file to create our Studentmasters model and declare all the public properties which we created in our MVC model.

export class StudentMasters {
        public StdID: number,
        public StdName: string,
        public Email: string,
        public Phone: string,
        public Address: string
    ) { }

Step 9: Creating HTML File

Next we need to create our html page to view result.To add the HTML file right click on wwwroot folder and click add new item , give the name as index.html and click Add.

Image 27

In HTMl file replace the below code. Here we can see first in header part we add all the script reference file and in script we load our boot file to run our app.In body part we display the result using the component selector name .In our app component we have given the selector name as “myapp1”.In this HTML to display the result we add tag like this     <my-app>Please wait...</my-app>

    <title>ASP.NET Core: AngularJS 2 Demo</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 1. Load libraries -->
    <!-- IE required polyfills -->
    <script src="/js/es6-shim.min.js"></script>
    <script src="/js/system-polyfills.js"></script>
    <!-- Angular2 libraries -->
    <script src="/js/angular2-polyfills.js"></script>
    <script src="/js/system.src.js"></script>
    <script src="/js/Rx.js"></script>
    <script src="/js/"></script>
    <script src="/js/"></script>
    <script src="/js/"></script>
    <!-- Bootstrap via SystemJS -->

                    defaultExtension: 'js'
                'lib': { defaultExtension: 'js' }
        System.import('app/boot').then(null, console.error.bind(console));


    <table style='width: 99%;table-layout:fixed;'>
                <table style="background-color:#FFFFFF;border: dashed 3px #6D7B8D; padding:10px;width: 99%;table-layout:fixed;" cellpadding="12" cellspacing="12">
                    <tr style="height: 30px; background-color:#f06a0a ; color:#FFFFFF ;border: solid 1px #659EC7;">
                        <td align="center">
                            <h3> SHANU ASP.NET Core1.0 Insert/Select Student Details to Database Using Angular2 and WEB API </h3>


                <!-- Application PlaceHolder -->
                <my-app>Please wait...</my-app>


So what is next we have successfully created our first Angular2 and Asp.Net core 1.0 web application and wait we have to do one more pending work to run our application? Yes we need to run our Grunt file to create our entire script file in our wwwroot scripts folder.

Step 8: Run the Grunt file using Visual Studio Task Runner Explorer

Now we need to run the Grunt file using Visual Studio Task Runner.

To view the Task Runner Click the menu View-> Other Windows,-> and click on Task Runner Explorer.

Image 28

We can also open Task Runner by right click on our Gruntfile.js in Solution Explorer and click on Task Runner Explorer.

Image 29

Now we can see our Task Runner Explorer.

Image 30

Click on GruntFile.js and click on refresh button at top left.

Image 31

Now we can see all the GruntFile has been added.

Image 32

Right click the default under Alias Task and click Run.

Image 33

Now our Grunt file has been successfully run in our project. When we add a script file we can see new app.js file will be created in our wwwroot folder.

Image 34

Run the Program:

Here we can see all the data from WEB API has been bind to our HTML page using Angular2.You can insert new Student details .Same like this you can add Update and Delete function to perform complete CRUD operations to maintain Student records.

Note: First create the Database and Table in your SQL Server .You can run the SQL Script from this article to create StudentsDB database and StudentMasters Table and also don’t forget to change the Connection string from “appsettings.json”

Image 35

History - 2016/08/06


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
Team Leader
India India
Microsoft MVP | Code Project MVP | CSharp Corner MVP | Author | Blogger and always happy to Share what he knows to others. MyBlog

My Interview on Microsoft TechNet Wiki Ninja Link

Comments and Discussions

QuestionUnsupported This version of Visual Studio is unable to open the following projects. Pin
Member 1162827214-Nov-17 19:49
Member 1162827214-Nov-17 19:49 
GeneralMy vote of 5 Pin
san2debug30-Oct-17 18:24
professionalsan2debug30-Oct-17 18:24 
QuestionASP.NET Core version upgrade Pin
Larry @Datasmith12-Feb-17 13:37
Larry @Datasmith12-Feb-17 13:37 
QuestionMy vote of 5 Pin
Ahmet Abdi9-Sep-16 18:28
Ahmet Abdi9-Sep-16 18:28 
Questionit is very useful Pin
Member 127131908-Sep-16 3:40
Member 127131908-Sep-16 3:40 
Questionvery useful and nice article Pin
M,AqibShehzad25-Aug-16 21:47
professionalM,AqibShehzad25-Aug-16 21:47 
QuestionUpgrade sample to release version of ASP.NET Core 1 Pin
zaktecs12-Aug-16 1:19
zaktecs12-Aug-16 1:19 
Praisegreat! Pin
Marcelo Lara10-Aug-16 4:01
Marcelo Lara10-Aug-16 4:01 
QuestionGood Pin
Vignesh Mani9-Aug-16 3:39
professionalVignesh Mani9-Aug-16 3:39 
PraiseNice one Pin
Oleg Kosmakov8-Aug-16 9:25
Oleg Kosmakov8-Aug-16 9:25 
GeneralRe: Nice one Pin
syed shanu8-Aug-16 14:07
professionalsyed shanu8-Aug-16 14:07 
QuestionProject structure Pin
Hipolito Lopez8-Aug-16 6:37
Hipolito Lopez8-Aug-16 6:37 
AnswerRe: Project structure Pin
Charlie Shin9-Aug-16 21:44
Charlie Shin9-Aug-16 21:44 
GeneralRe: Project structure Pin
Ken Skversky31-Dec-16 10:30
Ken Skversky31-Dec-16 10:30 
QuestionVery Ambitious Pin
Dewey7-Aug-16 19:46
Dewey7-Aug-16 19:46 
AnswerRe: Very Ambitious Pin
syed shanu7-Aug-16 19:50
professionalsyed shanu7-Aug-16 19:50 
QuestionNice Pin
Sacha Barber5-Aug-16 19:16
Sacha Barber5-Aug-16 19:16 
AnswerRe: Nice Pin
syed shanu7-Aug-16 14:55
professionalsyed shanu7-Aug-16 14:55 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.