Click here to Skip to main content
15,867,568 members
Articles / Web Development / HTML

ASP.NET Core,Angular2 CRUD with Animation using Template Pack, WEB API and EF 1.0.1

Rate me:
Please Sign up or sign in to vote.
4.94/5 (12 votes)
8 Mar 2017CPOL12 min read 23.3K   577   23   1
In this article, let’s see how to create a ASP.NET Core CRUD web application with Angular2 Animation using Template Pack, WEB API and EF 1.0.1

Introduction

Image 1

In this article, let’s see how to create a ASP.NET Core CRUD  web application with Angular2 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.

In this article, we will see the following:

Creating CRUD web Application ASP.NET Core and Angular2

  • 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).

Image 2

Presenting our CRUD Application more rich with simple Angular2 Animations like.

  • Angilar2 Animation for Fade-in Elements and controls.
  • Angilar2 Animation for Move Elements and controls from Left.
  • Angilar2 Animation for Move Elements and controls from Right.
  • Angilar2 Animation for Move Elements and controls from Top.
  • Angilar2 Animation for Move Elements and controls from Bottom.

Angilar2 Animation to enlarge Button on Click.

Image 3

For creating our ASP.NET Core, Angular2 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 method.
  • 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.

  1. First, download and install Visual Studio 2015 with Update 3 from this link.
  2. If you have Visual Studio 2015 and have not yet updated with update 3, download and install the Visual Studio 2015 Update 3 from this link
  3. Download and install .NET Core 1.0.1 
  4. Download and install TypeScript 2.0 
  5. Download and install Node.js v4.0 or above. I have installed V6.9.1 (Download link).
  6. Download and install Download ASP.NET Core Template Pack visz file from this link

Using the code

Step 1 Create a Database and Table

We will be using our SQL Server database for our WEB API and EF. 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 our project.

SQL
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','syedshanumcain@gmail.com','01030550007','Madurai,India')  
  
INSERT INTO [StudentMasters]   ([StdName],[Email],[Phone],[Address])  
     VALUES ('Afraz','Afraz@afrazmail.com','01030550006','Madurai,India')  
       
INSERT INTO [StudentMasters]   ([StdName],[Email],[Phone],[Address])  
     VALUES ('Afreen','Afreen@afreenmail.com','01030550005','Madurai,India')  
       
       
     select * from [StudentMasters] 

Step 2- Create ASP.NET Core Angular 2 application

After installing all the prerequisites listed above and ASP.NET Core Template, click Start >> Programs >> Visual Studio 2015 >> Visual Studio 2015, on your desktop. Click New >> Project. Select Web >> ASP.NET Core Angular 2 Starter. Enter your project name and click OK.

Image 4

After creating ASP.NET Core Angular 2 application, wait for a few seconds. You will see that all the dependencies are automatically restoring.

Image 5

What is new in ASP.NET Core Template Pack Solution?

Image 6

  1. WWWroot

We can see all the CSS,JS files are added under in “dist” folder .”main-client.js” file is the important file as all the Angular2 result will be compiled and result’s will be loaded from this “js” file to our html file.

Image 7

  1. ClientApp Folder:

We can see a new folder ClientApp inside our project solution. This folder contains all Angular2 related applications like Modules,Components and etc.We can add all our Angular 2 related Modules,Component,Template HTML file all under this folder we can see in details about how to create our own Angular2 application here below in our article.

In Components folder under app folder we can see many subfolders like app. counter, fetchdata, home and navemenu. By default, all this sample application has been created and when we run our application we can see all the sample Angular2 application results. 

Image 8

When we run the application, we can see in left side as navigation and in right side contains data. All the Angular2 Sample will be loaded from the above folder.

Image 9

3) Controllers Folder: This is our MVC Controller folder, we can create both MVC and Web API Controller in this folder.

4) View Folder: This is our MVC View folder.

5) Other Important files

We can also see other important ASP.NET Core important other files like

project.json : ASP.NET Core dependency list can be found in this file, We will be adding our Entity Frame work in dependency section of this file.

package.json : This is another important file as all Angular2 related dependency list will be added here by default all the Angular2 related dependency’s has been added here 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 the Project.JSON File and in dependencies add the below line to.

Note : Here we have used EF version 1.0.1.

JavaScript
"Microsoft.EntityFrameworkCore.SqlServer": "1.0.1",
    "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"

Image 10

When we save the project,.json file we can see the Reference was been Restoring.

Image 11

After few second we can see Entity framework package has been restored and all reference has been added.

Image 12

Adding Connection String

To add the 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 13

In this appsettings.json file add our connection string 

XML
"ConnectionStrings": {
    "DefaultConnection": "Server=YOURDBSERVER;Database=StudentsDB;user id=SQLID;password=SQLPWD;Trusted_Connection=True;MultipleActiveResultSets=true;"
  },

Note change the SQL connection string as per your local connection.

Image 14

Next step is we create a folder named “Data” to create our model and DBContext class.

Image 15

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.

Image 16

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

C#
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 for establishing connection to 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.

Image 17

In this class we inherit DbContext and created Dbset for our students table.

C#
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 below code in Startup.cs file under ConfigureServices method.

C#
// 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.

Image 18

Click ASP.NET in right side > Click Web API Controller Class. Enter the name as “StudentMastersAPI.cs” and click Add.

Image 19

As we all know Web API is a simple and easy way to build HTTP Services for Browsers and Mobiles.

Web API has the following four methods 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 be get all student information’s from StudentMasters Table.

C#
[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 for insert in to the Student Master Table.

C#
// 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 Updated 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.

C#
// 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.

C#
// 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 for get is api/StudentMastersAPI/Student
Run the program and paste the above API path to test our output.

Image 20

Working with Angular2

We create all Angular2 related App, Module, Services, Component and html template under ClientApp/App folder.

We create “students” folder under app folder to create our typescript and html file for displaying Student details.

Image 21

Step 5 Working with Angular2 Animation

Image 22

Angular animations are all build on top of the standard Web Animations API .Kindly check this reference link which explains more detail about Angular2 Animations https://angular.io/docs/ts/latest/guide/animations.html

Adding Animation in web applications will give more rich look for our web site. Here in this application we will be using Angular2 Animation for Fade-in Enlarge controls on click event and move 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 that we edit the Home Component for creating our Angular2 Animation.

Import part:

For using the Angular2 Animation we need to first import “trigger, state, style, transition, animate”.

Our import will look like this

JavaScript
import {Component, Input, trigger, state, style, transition, animate, keyframes} from <a href="mailto:'@angular/core'">'@angular/core'</a>;

Component Part

In component we need to add animations: [] for performing our animation with triggers.

The trigger is used to connect Component with our HTML Template for example here let’s see on creating a simple Animation to change the color and resize the Button on click event.

For this first we create a trigger with name as “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 perform 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 actual location of button.When the page loads the button will be start from -200 Y-axis place and move toward up till the actual button location that is 'translateY(0)'

JavaScript
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 for performing the animation like below.Here we have add the animation for div tag.

JavaScript
<div  [@moveBottom]= ‘moveBottom’>
        ASP.NET  Angular2
    </div>

Same like Bottom we do rest of Animations for,Left,Right,Top and Fade-In, here is the complete code for Home Animation component.

JavaScript
import { Component, Input, trigger,  state,  style,  transition,   animate,    keyframes } from <a href="mailto:'@angular/core'">'@angular/core'</a>;

@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.

HTML
<h1 [@fadeIn]='animStatus'>ASP.NET Core,Angular2 CRUD with Animation using Template Pack, WEB API and EF 1.0.1  </h1>
<div class="column">


    <div style="background-color:#0094ff;color:#FFFFFF;font-size:xx-large;width:340px;height:50px;text-shadow:  -2px -1px 0px #000,
         0px -1px 0px #000,
         1px -1px 0px #000,
        -2px  0px 0px #000,
         1px  0px 0px #000,
        -2px  1px 0px #000,
         0px  1px 0px #000,
         1px  1px 0px #000;text-align:center;display:inline-block;
                              border-color:#a2aabe;border-style:dashed;border-width:2px;" [@moveBottom]='moveBottom'>

        ASP.NET  Angular2

    </div>

    <div style="background-color:#ff00dc;color:#FFFFFF;font-size:xx-large;width:340px;height:50px;text-shadow:  -2px -1px 0px #000,
         0px -1px 0px #000,
         1px -1px 0px #000,
        -2px  0px 0px #000,
         1px  0px 0px #000,
        -2px  1px 0px #000,
         0px  1px 0px #000,
         1px  1px 0px #000;text-align:center;display:inline-block;
                              border-color:#a2aabe;border-style:dashed;border-width:2px;" [@moveTop]='moveTop'>

        CRUD

    </div>

    <div style="background-color:#3ab64a;color:#FFFFFF;font-size:xx-large;width:340px;height:50px;text-shadow:  -2px -1px 0px #000,
         0px -1px 0px #000,
         1px -1px 0px #000,
        -2px  0px 0px #000,
         1px  0px 0px #000,
        -2px  1px 0px #000,
         0px  1px 0px #000,
         1px  1px 0px #000;text-align:center;display:inline-block;
                              border-color:#a2aabe;border-style:dashed;border-width:2px;" [@moveRight]='moveRight'>

        Animation

    </div>
</div>
<div class="column">
    <h2>Created by : </h2>
    <div style="background-color:#ff6a00;color:#FFFFFF;font-size:xx-large;width:320px;height:50px;text-shadow:  -2px -1px 0px #000,
         0px -1px 0px #000,
         1px -1px 0px #000,
        -2px  0px 0px #000,
         1px  0px 0px #000,
        -2px  1px 0px #000,
         0px  1px 0px #000,
         1px  1px 0px #000;text-align:center;
                              border-color:#a2aabe;border-style:dashed;border-width:2px;" [@movelLeft]='movelLeft'>

        {{myName}}

    </div>
</div>

Step – 6 Creating our Component TypeScript

Right Click on students folder and click on add new Item. Select Client-side from left side and select TypeScript File and name the file as “students.component.ts” and click Add.

Image 23

In students.component.ts file we have three parts first is the,

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

 First, we import angular files to be used in our component here we import http for using http client in our Angular2 component along with Animation.

In component, we have selector, animation and template. Selector is to give a name for this app and in our html file we use this selector name to display in our html page. Animation is used to perform animation for our Angular2 application. As we have seen in our home component we have used Move, Left, Right, Bottom, Top and fade-In, we will be using the same animation in our CRDU page.
In template we give our output html file name. here we will create on html file as “students.component.html”.

Export Class is the main class where we do all our business logic and variable declaration to be used in our component template. In this class we get the API method result and bind the result to the student array and also we will be perform rest or Post, Put and Delete method to perform our CRUD operations.

JavaScript
import {
    Component, Input, trigger,
    state,
    style,
    transition,
    animate,
    keyframes } from <a href="mailto:'@angular/core'">'@angular/core'</a>;
import { Http, Response,  Headers, RequestOptions } from <a href="mailto:'@angular/http'">'@angular/http'</a>;
import { FormsModule } from <a href="mailto:'@angular/forms'">'@angular/forms'</a>;

@Component({
    selector: 'students'
   ,
    
    animations: [

        trigger('buttonReSize', [
            state('inactive', style({
                transform: 'scale(1)',
                backgroundColor: '#f83500'
            })),
            state('active', style({
                transform: 'scale(1.4)',
                backgroundColor: '#0094ff'
            })),
            transition('inactive => active', animate('100ms ease-in')),
            transition('active => inactive', animate('100ms ease-out'))
        ]),

        trigger('moveBottom', [

            transition('void => *', [
                animate(900, 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(900, 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(900, 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(900, 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('fadeIn', [
            transition('* => *', [
                animate('1s', keyframes([
                    style({ opacity: 0, transform: 'translateX(0)', offset: 0 }),
                    style({ opacity: 1, transform: 'translateX(0)', offset: 1 }),
                ]))
            ])
        ]),

      
    ],
    template: require('./students.component.html')
})

export class studentsComponent {
      // to get the Student Details
    public student: StudentMasters[] = [];
    // to hide and Show Insert/Edit
    AddstudetnsTable: Boolean = false;
    // To stored Student Informations for insert/Update and Delete
    public StdIDs = "0";
    public StdNames  = "";
    public Emails = "";
    public Phones = "";
    public Addresss= "";

    //For display Edit and Delete Images
    public imgEdit = require("./Images/edit.gif");
    public imgDelete = require("./Images/delete.gif");

    myName: string;
    //for animation status
    animStatus: string = 'inactive';
    constructor(public http: Http) {
        this.myName = "Shanu";
        this.AddstudetnsTable = false;
        this.getData();
    }

    //for Animation to toggle Active and Inactive
    animButton() {
        this.animStatus = (this.animStatus === 'inactive' ? 'active' : 'inactive');
    }

    //to get all the Student data from Web API
    getData()
    {
        this.http.get('/api/StudentMastersAPI/Student').subscribe(result => {
            this.student = result.json();
        });
    }

    // to show form for add new Student Information
    AddStudent() {
        this.animButton();
        this.AddstudetnsTable = true;
    this.StdIDs = "0";
    this.StdNames = "";
    this.Emails = "";
    this.Phones = "";
    this.Addresss = "";
    }

    // to show form for edit Student Information
    editStudentsDetails(StdID, StdName, Email, Phone, Address) {
        this.animButton();
        this.AddstudetnsTable = true;
        this.StdIDs = StdID;
        this.StdNames = StdName;
        this.Emails = Email;
        this.Phones = Phone;
        this.Addresss = Address;
    }

    // If the studentid is 0 then insert the student infromation using post and if the student id is more than 0 then edit using put mehod
    addStudentsDetails(StdID, StdName, Email, Phone, Address) {
        alert(StdName);
        var headers = new Headers();
        headers.append('Content-Type', 'application/json; charset=utf-8');
        if (StdID == 0)
        {
            this.http.post('api/StudentMastersAPI', JSON.stringify({ StdID: StdID, StdName: StdName, Email: Email, Phone: Phone, Address: Address }), { headers: headers }).subscribe();
            alert("Student Detail Inserted");
        }
        else
        {
            this.http.put('api/StudentMastersAPI/' + StdID, JSON.stringify({ StdID: StdID, StdName: StdName, Email: Email, Phone: Phone, Address: Address }), { headers: headers }).subscribe();
            alert("Student Detail Updated");
        }      
     
        this.AddstudetnsTable = false;
        this.getData();        
    }

    //to Delete the selected student detail from database.
    deleteStudentsDetails(StdID) {        
        var headers = new Headers();
        headers.append('Content-Type', 'application/json; charset=utf-8');
      
        this.http.delete('api/StudentMastersAPI/' + StdID, { headers: headers }).subscribe();
            alert("Student Detail Deleted");
            this.getData();       
    }

    closeEdits()
    {
        this.AddstudetnsTable = false;
        this.StdIDs = "0";
        this.StdNames = "";
        this.Emails = "";
        this.Phones = "";
        this.Addresss = "";
    }
}

export interface StudentMasters {
    stdID: number;
    stdName: string;
    email: string;
    phone: string;
    address: string;
}

Step – 7 Creating our HTML Template File

Right Click on students folder and click on add new Item. Select Client-side from left side and select html File and name the file as “students.component.html” and click Add.

Image 24

Write the below html code to bind the result in our html page.

HTML
<h1 [@fadeIn]='animStatus'>ASP.NET Core,Angular2 CRUD with Animation using Template Pack, WEB API and EF 1.0.1  </h1>
 <div class="column">

     <h2>Created by : </h2>
    <div style="background-color:#ff6a00;color:#FFFFFF;font-size:xx-large;width:260px;height:50px;text-shadow:  -2px -1px 0px #000,
         0px -1px 0px #000,
         1px -1px 0px #000,
        -2px  0px 0px #000,
         1px  0px 0px #000,
        -2px  1px 0px #000,
         0px  1px 0px #000,
         1px  1px 0px #000;text-align:center;
                              border-color:#a2aabe;border-style:dashed;border-width:2px;"   [@movelLeft]='animStatus'>
        
            {{myName}}
     
    </div>
</div>

<hr style="height: 1px;color: #123455;background-color: #d55500;border: none;color: #d55500;" />
<p *ngIf="!student"><em>Loading Student Details please Wait ! ...</em></p>

<table id="tblContainer" style='width: 99%;table-layout:fixed;'>
    <tr>
        <td>
            <table style="background-color:#FFFFFF; border: dashed 3px #FFFFFF; padding: 5px;width: 99%;table-layout:fixed;" cellpadding="2"
                   cellspacing="2">
                <tr style="height: 30px;  color:#123455 ;border: solid 1px #659EC7;">
                    <td width="40px">&nbsp;</td>
                    <td width="50%">
                        <h1> Add New Students Information <strong style="color:#0094ff"> </strong></h1>
                      
                    </td>
                    <td align="right">
                        <button (click)=AddStudent() style="background-color:#f83500;color:#FFFFFF;font-size:large;width:260px;height:50px;
                              border-color:#a2aabe;border-style:dashed;border-width:2px;" [@moveRight]='animStatus'  [@buttonReSize]='animStatus'>
                            Add New Studetnt Information
                        </button>
                        &nbsp;
                    </td>
                </tr>
            </table>

        </td>
    </tr>
    <tr>
        <td>
            <hr style="height: 1px;color: #123455;background-color: #d55500;border: none;color: #d55500;" />
        </td>
    </tr>
    <tr *ngIf="AddstudetnsTable">
        <td  [@fadeIn]='animStatus'>
            <table>
                <tr>
                    <td>

                        <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;">
                                <td width="40">
                                    &nbsp;
                                </td>
                                <td>
                                    <h2>Insert/Edit Student Details : </h2>
                                </td>
                            </tr>
                            <tr>
                                <td width="100">
                                    &nbsp;
                                </td>
                                <td>
                                    <table style="color:#9F000F;font-size:large; padding :5px;" cellpadding="12" cellspacing="16">
                                        <tr>
                                            <td><b>Students ID: </b> </td>
                                            <td>
                                                <input type="text" #StdID (ngModel)="StdIDs" value="{{StdIDs}}" style="background-color:tan" readonly>
                                            </td>
                                            <td width="20">&nbsp;</td>
                                            <td><b>Students Name: </b> </td>
                                            <td>
                                                <input type="text" #StdName (ngModel)="StdNames" value="{{StdNames}}">
                                            </td>
                                            <td></td>
                                        </tr>
                                        <tr>
                                            <td><b>Email: </b> </td>
                                            <td>
                                                <input type="text" #Email (ngModel)="Emails" value="{{Emails}}">
                                            </td>
                                            <td width="20">&nbsp;</td>
                                            <td><b>Phone: </b> </td>
                                            <td>
                                                <input type="text" #Phone (ngModel)="Phones" value="{{Phones}}">
                                            </td>
                                            <td></td>
                                        </tr>
                                        <tr>
                                            <td><b>Address: </b> </td>
                                            <td  >
                                                <input type="text" #Address (ngModel)="Addresss" value="{{Addresss}}">

                                            </td>
                                            <td width="20">&nbsp;</td>
                                            <td align="right" colspan="2">
                                                <button (click)=addStudentsDetails(StdID.value,StdName.value,Email.value,Phone.value,Address.value) style="background-color:#428d28;color:#FFFFFF;font-size:large;width:220px;
                              border-color:#a2aabe;border-style:dashed;border-width:2px;"  [@moveBottom]='animStatus' >
                                                    Save
                                                </button>

                                            
                                              
                                            </td>
                                            <td>
                                                &nbsp;&nbsp;&nbsp;
                                                <button (click)=closeEdits() style="background-color:#334668;color:#FFFFFF;font-size:large;width:180px;
                              border-color:#a2aabe;border-style:dashed;border-width:2px;"  [@moveTop]='animStatus' >
                                                    Close
                                                </button>
                                            </td>
                                        </tr>
                                    </table>
                                </td>
                            </tr>

                        </table>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <hr style="height: 1px;color: #123455;background-color: #d55500;border: none;color: #d55500;" />
                    </td>
                </tr>
            </table>
        </td>

                </tr>
                <tr>
                    <td  [@moveBottom]='animStatus' >

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

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

                            </tr>
                            <tbody *ngFor="let StudentMasters  of student"  [@moveTop]='animStatus'>
                                <tr>
                                    <td align="center" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">
                                        <span style="color:#9F000F">
                                            <img src="{{imgEdit}}"  style="height:32px;width:32px" (click)=editStudentsDetails(StudentMasters.stdID,StudentMasters.stdName,StudentMasters.email,StudentMasters.phone,StudentMasters.address)>
                                        </span>

                                    </td>

                                    <td align="center" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">
                                        <span style="color:#9F000F">
                                            <img src="{{imgDelete}}" style="height:32px;width:32px" (click)=deleteStudentsDetails(StudentMasters.stdID)>
                                        </span>

                                    </td>

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

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

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

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

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

Step – 8 Adding Students Navigation menu

We can add our newly created student details menu in existing menu.

TO add our new navigation menu open the “navmenu.component.html” under navmenu menu.write the below code to add our navigation menu link for students.

HTML
<li [routerLinkActive]="['link-active']">
                    <a [routerLink]="['/students']">
                        <span class='glyphicon glyphicon-th-list'></span> Students
                    </a>
                </li>

Step – 9 App Module

App Module is root for all file and we can find the app.module.ts under ClientApp\ app

Import our students component

JavaScript
import { studentsComponent } from './components/students/students.component';

Next in @NGModule add studentsComponent
In routing add our students path.
The code will be looks like this

JavaScript
import { NgModule } from <a href="mailto:'@angular/core'">'@angular/core'</a>;
import { RouterModule } from <a href="mailto:'@angular/router'">'@angular/router'</a>;
import { UniversalModule } from 'angular2-universal';
import { AppComponent } from './components/app/app.component'
import { NavMenuComponent } from './components/navmenu/navmenu.component';
import { HomeComponent } from './components/home/home.component';
import { FetchDataComponent } from './components/fetchdata/fetchdata.component';
import { CounterComponent } from './components/counter/counter.component';
import { studentsComponent } from './components/students/students.component';

@NgModule({
    bootstrap: [ AppComponent ],
    declarations: [
        AppComponent,
        NavMenuComponent,
        CounterComponent,
        FetchDataComponent,
        HomeComponent,
        studentsComponent
    ],
    imports: [
        UniversalModule, // Must be first import. This automatically imports BrowserModule, HttpModule, and JsonpModule too.
        RouterModule.forRoot([
            { path: '', redirectTo: 'home', pathMatch: 'full' },
            { path: 'home', component: HomeComponent },
            { path: 'counter', component: CounterComponent },
            { path: 'fetch-data', component: FetchDataComponent },
            { path: 'students', component: studentsComponent },
            { path: '**', redirectTo: 'home' }
        ])
    ]
})
export class AppModule {
}

Step – 10 Build and run the application

Build and run the application and you can see our Home page with animation and  Students CRUD page Animation.

Image 25

Points of Interest

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”.

History

Angular2ASPCORE.zip - 2017/03/02

License

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

 
QuestionAdding popup functionality for the "Insert/Edit Student Details" Pin
Member 1305613123-Mar-17 21:52
Member 1305613123-Mar-17 21:52 

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.