ASP.NET Core And Angular 2 Master Detail HTML Grid Using Web API And EF 1.0.1

Introduction

In this article, let’s see how to create our own ASP.NET Core, Angular 2 Master Detail HTML Grid using Template pack, Entity Framework 1.0.1, and Web API to display Master and Detail data from database to our Angular2 and ASP.NET Core web application.

Kindly read my previous articles which explains in depth about getting started with ASP.NET Core Template Pack.

In this article, let’s see:

  • Creating sample database and Student Master and Detail Table in SQL Server to display in our web application.
  • How to create ASP.NET Core Angular 2 Starter Application (.NET Core) using Template pack.
  • Creating EF, DBContext Class and Model Class.
  • Creating Web API.
  • Creating our first component TypeScript file to get Web API JSON result using HTTP Module.
  • Creating our first component HTML file to bind the data to Master and Detail HTML Grid.

This article will explain how to create a Master /Detail Table and bind the Master related details in inner HTML table to show the output as Master/Detail Grid. Here, in this article, we have used the Student Master and Student Detail relation to show the Master/Detail Grid. In Student Master, we store student ID, Name, Email, Phone and Address. In Student Details, we store the students' final exam results for displaying Student Major, Studying Year with Term, and Grade details.

Here, in the below image, we can see that when the user clicks on the Student ID “2”,  then the next details Grid was being displayed to show student results in detail by Major,Year, Term, and Grade.

Here, we are displaying student details by each student Id.



Prerequisites

Make sure you have installed all the following prerequisites in your computer. If not, then download and install them 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
  6. Download and install Download ASP.NET Core Template Pack visz file

Code Part

Step 1 Create a Database and Table

We will create a Student Master and Student Detail table to be used for the Master and Detail Grid data binding. 

The following is the script to create a database, table and sample insert query. Run this script in your SQL Server. I have used SQL Server 2014.

  1. USEMASTER  
  2. GO  
  3. --1) Check  
  4. --  
  5. for the Database Exists.If the database is exist then drop and create new DB  
  6. IFEXISTS(SELECT[name] FROMsys.databasesWHERE[name] = 'StudentsDB')  
  7. DROPDATABASEStudentsDB  
  8. GO  
  9. --CREATEDATABASEStudentsDB  
  10. GO  
  11. USEStudentsDB  
  12. GO  
  13. --1) //////////// StudentMasters  
  14. IFEXISTS(SELECT[name] FROMsys.tablesWHERE[name] = 'StudentMasters')  
  15. DROPTABLEStudentMasters  
  16. GO  
  17. CREATETABLE[dbo].[StudentMasters](  
  18.         [StdID] INTIDENTITYPRIMARYKEY, [StdName][varchar](100) NOTNULL, [Email][varchar](100) NOTNULL, [Phone][varchar](20) NOTNULL, [Address][varchar](200) NOTNULL)  
  19.     --insert sample data to Student Master table  
  20. INSERTINTO[StudentMasters]([StdName], [Email], [Phone], [Address])  
  21. VALUES('Shanu''syedshanumcain@gmail.com''01030550007''Madurai,India')  
  22. INSERTINTO[StudentMasters]([StdName], [Email], [Phone], [Address])  
  23. VALUES('Afraz''Afraz@afrazmail.com''01030550006''Madurai,India')  
  24. INSERTINTO[StudentMasters]([StdName], [Email], [Phone], [Address])  
  25. VALUES('Afreen''Afreen@afreenmail.com''01030550005''Madurai,India')  
  26. select * from[StudentMasters]  
  27. IFEXISTS(SELECT[name] FROMsys.tablesWHERE[name] = 'StudentDetails')  
  28. DROPTABLEStudentDetails  
  29. GO  
  30. CREATETABLE[dbo].[StudentDetails](  
  31.     [StdDtlID] INTIDENTITYPRIMARYKEY, [StdID] INT, [Major][varchar](100) NOTNULL, [Year][varchar](30) NOTNULL, [Term][varchar](30) NOTNULL, [Grade][varchar](10) NOTNULL)  
  32. INSERTINTO[StudentDetails]([StdID], [Major], [Year], [Term], [Grade])  
  33. VALUES(1, 'Computer Science''FirstYear''FirstTerm''A')  
  34. INSERTINTO[StudentDetails]([StdID], [Major], [Year], [Term], [Grade])  
  35. VALUES(1, 'Computer Science''FirstYear''SecondTerm''B')  
  36. INSERTINTO[StudentDetails]([StdID], [Major], [Year], [Term], [Grade])  
  37. VALUES(1, 'Computer Science''SecondYear''FirstTerm''C')  
  38. INSERTINTO[StudentDetails]([StdID], [Major], [Year], [Term], [Grade])  
  39. VALUES(2, 'Computer Engineer''ThirdYear''FirstTerm''A')  
  40. INSERTINTO[StudentDetails]([StdID], [Major], [Year], [Term], [Grade])  
  41. VALUES(2, 'Computer Engineer''ThirdYear''SecondTerm''A')  
  42. INSERTINTO[StudentDetails]([StdID], [Major], [Year], [Term], [Grade])  
  43. VALUES(3, 'English''First Year''FirstTerm''C')  
  44. INSERTINTO[StudentDetails]([StdID], [Major], [Year], [Term], [Grade])  
  45. VALUES(13, 'Economics''First Year''FirstTerm''A')  
  46. select * fromStudentDetails  
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.

HTML

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

HTML

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 too.
  1. "Microsoft.EntityFrameworkCore.SqlServer""1.0.1""Microsoft.EntityFrameworkCore.Tools""1.0.0-preview2-final"  
HTML

When we save the project.json file, we can see the Reference has been restored.

HTML

After few seconds, we can see Entity Framework package has been restored and all references have been added.

HTML

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 like below image by default.

HTML

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

HTML

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

HTML

Creating Model Class for Student Master

We can create a model by adding a new class file in our Data Folder. Right click the Data folder and click Add > Class. Enter the class name as StudentMasters and click "Add".

HTML

Now, in this class, we first create property variable, then add studentMaster. We will be using this in our WEB API Controller.
  1. using System;  
  2. usingSystem.Collections.Generic;  
  3. usingSystem.Linq;  
  4. usingSystem.Threading.Tasks;  
  5. usingSystem.ComponentModel.DataAnnotations;  
  6. namespace Angular2ASPCORE.Data {  
  7.     publicclassStudentMasters {  
  8.         [Key]  
  9.         publicintStdID {  
  10.             get;  
  11.             set;  
  12.         }  
  13.         [Required]  
  14.         [Display(Name = "Name")]  
  15.         publicstringStdName {  
  16.             get;  
  17.             set;  
  18.         }  
  19.         [Required]  
  20.         [Display(Name = "Email")]  
  21.         publicstring Email {  
  22.             get;  
  23.             set;  
  24.         }  
  25.         [Required]  
  26.         [Display(Name = "Phone")]  
  27.         publicstring Phone {  
  28.             get;  
  29.             set;  
  30.         }  
  31.         publicstring Address {  
  32.             get;  
  33.             set;  
  34.         }  
  35.     }  
  36. }  
Creating Model Class for Student Detail

We can create a model by adding a new class file in our Data folder. Right click Data folder and click Add >Class. Enter the class name as StudentDetails and click Add.

HTML

In this class, we first create property variable, then add StudentDetails. We will be using this in our Web API Controller.
  1. publicclassStudentDetails {  
  2.     [Key]  
  3.     publicintStdDtlID {  
  4.         get;  
  5.         set;  
  6.     }  
  7.     [Required]  
  8.     [Display(Name = "StudentID")]  
  9.     publicintStdID {  
  10.         get;  
  11.         set;  
  12.     }  
  13.     [Required]  
  14.     [Display(Name = "Major")]  
  15.     publicstring Major {  
  16.         get;  
  17.         set;  
  18.     }  
  19.     [Required]  
  20.     [Display(Name = "Year")]  
  21.     publicstring Year {  
  22.         get;  
  23.         set;  
  24.     }  
  25.     [Required]  
  26.     [Display(Name = "Term")]  
  27.     publicstring Term {  
  28.         get;  
  29.         set;  
  30.     }  
  31.     publicstring Grade {  
  32.         get;  
  33.         set;  
  34.     }  
  35. }  
Creating Database Context

DBContext is Entity Framework Class for establishing a 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 > Class. Enter the class name as StudentContext and click Add.

HTML

In this class, we inherit DbContext and created Dbset for our studentMasters and StudentDetails table.
  1. using System;  
  2. usingSystem.Collections.Generic;  
  3. usingSystem.Linq;  
  4. usingSystem.Threading.Tasks;  
  5. usingMicrosoft.EntityFrameworkCore;  
  6. namespace Angular2ASPCORE.Data {  
  7.     publicclassstudentContext: DbContext {  
  8.         publicstudentContext(DbContextOptions < studentContext > options): base(options) {}  
  9.         publicstudentContext() {}  
  10.         publicDbSet < StudentMasters > StudentMasters {  
  11.             get;  
  12.             set;  
  13.         }  
  14.         publicDbSet < StudentDetails > StudentDetails {  
  15.             get;  
  16.             set;  
  17.         }  
  18.     }  
  19. }  
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.
  1. // Add Entity framework .  
  2. services.AddDbContext < studentContext > (options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));  
Step 4 Creating Web API

To create our WEB API Controller, right click Controllers folder. Click "Add" and click "New Item".

HTML

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

HTML

In this, we are using only "Get" method to get all the student result from database and bind the final result using Angular 2 to HTML file.

Here, in this Web API, we get both Student Master, Student Details, and Student Details load by condition student ID.
  1. [Produces("application/json")]  
  2. [Route("api/StudentMastersAPI")]  
  3. publicclassStudentMastersAPI: Controller {  
  4.     privatereadonlystudentContext _context;  
  5.     publicStudentMastersAPI(studentContext context) {  
  6.         _context = context;  
  7.     }  
  8.     // GET: api/values  
  9.     // For Student Master  
  10.     [HttpGet]  
  11.     [Route("Student")]  
  12.     publicIEnumerable < StudentMasters > GetStudentMasters() {  
  13.         return _context.StudentMasters;  
  14.     }  
  15.     // GET: api/values  
  16.     // For Student Detail  
  17.     [HttpGet]  
  18.     [Route("Details")]  
  19.     publicIEnumerable < StudentDetails > GetStudentDetails() {  
  20.         return _context.StudentDetails;  
  21.     }  
  22.     // For Student Detail with studentid to load by student ID  
  23.     // GET api/values/5  
  24.     [HttpGet]  
  25.     [Route("Details/{id}")]  
  26.     publicIEnumerable < StudentDetails > GetStudentDetails(int id) {  
  27.         return _context.StudentDetails.Where(i => i.StdID == id).ToList();  
  28.     }  
  29. }  
To test it, we can run our project and copy the get method API path. Here, we can see our API path for get -
api/StudentMastersAPI/Student

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

HTML

To get the Student Details by Student ID. Here, we can see all the Student Details for Student ID=1 has been loaded.

api/StudentMastersAPI/Details/1

HTML

Working with Angular2

We create all Angular 2 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 for displaying Student details.

HTML

Step 5 Creating our First Component TypeScript

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

HTML

In students.component.ts file, we have three parts -
  1. import part
  2. component part
  3. class for writing our business logic.

First, we import Angular files to be used in our component. Here, we import HTTP  for using HTTP client in our Angular 2 component.

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

In template, we give our output html file name. Here, we will create an html file as “students.component.html”.

Export Class is the main class where we do all our business logic and variable declaration that is used in our component template. In this class, we get the API method result and bind the result to the Student array.

Here, we first get all the Student Master data from Web API to bind in our html page. We have created one more function named “getStudentsDetails”  to which we pass the Student ID to load only the selected Student ID related data from Student Detail tables. We call this function from button click of each Student Master.

  1. import {  
  2.     Component  
  3. } from '@angular/core';  
  4. import {  
  5.     Http  
  6. } from "@angular/http";  
  7. @Component({  
  8.     selector: 'students',  
  9.     template: require('./students.component.html')  
  10. })  
  11. exportclassstudentsComponent {  
  12.     public student: StudentMasters[] = [];  
  13.     publicstudentdetails: StudentDetails[] = [];  
  14.     myName: string;  
  15.     activeRow: string = "0";  
  16.     constructor(public http: Http) {  
  17.         this.myName = "Shanu";  
  18.         this.getStudentMasterData();  
  19.     }  
  20.     getStudentMasterData() {  
  21.         this.http.get('/api/StudentMastersAPI/Student').subscribe(result => {  
  22.             this.student = result.json();  
  23.         });  
  24.     }  
  25.     getStudentsDetails(StudID) {  
  26.         this.http.get('/api/StudentMastersAPI/Details/' + StudID).subscribe(result => {  
  27.             this.studentdetails = result.json();  
  28.         });  
  29.         this.activeRow = StudID;  
  30.     }  
  31. }  
  32. //// For Student Master  
  33. exportinterfaceStudentMasters {  
  34.     stdID: number;  
  35.     stdName: string;  
  36.     email: string;  
  37.     phone: string;  
  38.     address: string;  
  39. }  
  40. // For Student Details  
  41. exportinterfaceStudentDetails {  
  42.     StdDtlID: number;  
  43.     stdID: number;  
  44.     Major: string;  
  45.     Year: string;  
  46.     Term: string;  
  47.     Grade: string;  
  48. }  
Step 6 Creating our First Component HTML File

Right click on Students folder and click on "Add New Item". Select Client-side from left side and select html file. Name the file “students.component.html” and click "Add".

HTML

Write the below HTML code to bind the result in our html page. Here, we have first created HTML Table for loading the Student Master data with Detail Button.

On the Detail button click, we load the Student Details for selected students and bind the result according to the table row.
  1. <h1>Angular 2 with ASP.NET Core Template Pack, WEB API and EF 1.0.1 </h1>  
  2. <hr/>  
  3. <h2>My Name is : {{myName}}</h2>  
  4. <hr/>  
  5. <h1>Students Details :</h1>  
  6. <p*ngIf="!student"><em>Loading Student Details please Wait ! ...</em></p>  
  7.     <!--<pre>{{studentdetails|json}}</pre>-->  
  8.     <tableclass='table' style="background-color:#FFFFFF; border:2px#6D7B8D; padding:5px;width:99%;table-layout:fixed;" cellpadding="2" cellspacing="2" *ngIf="student">  
  9.         <trstyle="height: 30px; background-color:#336699 ; color:#FFFFFF ;border: solid1px#659EC7;">  
  10.             <tdwidth="80" align="center">  
  11.                 </td>  
  12.                 <tdwidth="80" align="center">Student ID</td>  
  13.                     <tdwidth="240" align="center">Student Name</td>  
  14.                         <tdwidth="240" align="center">Email</td>  
  15.                             <tdwidth="120" align="center">Phone</td>  
  16.                                 <tdwidth="340" align="center">Address</td>  
  17.                                     </tr>  
  18.                                     <tbody*ngFor="let StudentMasters of student">  
  19.                                         <tr>  
  20.                                             <tdalign="center" style="border: solid1px#659EC7; padding: 5px;table-layout:fixed;">  
  21.                                                 <button(click)=getStudentsDetails(StudentMasters.stdID)style="background-color:#334668;color:#FFFFFF;font-size:large;width:80px;  
  22. border-color:#a2aabe;border-style:dashed;border-width:2px;"> Detail </button>  
  23.                                                     </td>  
  24.                                                     <tdalign="center" style="border: solid1px#659EC7; padding: 5px;table-layout:fixed;">  
  25.                                                         <spanstyle="color:#9F000F">{{StudentMasters.stdID}}</span>  
  26.                                                             </td>  
  27.                                                             <tdstyle="border: solid1px#659EC7; padding: 5px;table-layout:fixed;">  
  28.                                                                 <spanstyle="color:#9F000F">{{StudentMasters.stdName}}</span>  
  29.                                                                     </td>  
  30.                                                                     <tdstyle="border: solid1px#659EC7; padding: 5px;table-layout:fixed;">  
  31.                                                                         <spanstyle="color:#9F000F">{{StudentMasters.email}}</span>  
  32.                                                                             </td>  
  33.                                                                             <tdalign="center" style="border: solid1px#659EC7; padding: 5px;table-layout:fixed;">  
  34.                                                                                 <spanstyle="color:#9F000F">{{StudentMasters.phone}}</span>  
  35.                                                                                     </td>  
  36.                                                                                     <tdstyle="border: solid1px#659EC7; padding: 5px;table-layout:fixed;">  
  37.                                                                                         <spanstyle="color:#9F000F">{{StudentMasters.address}}</span>  
  38.                                                                                             </td>  
  39.                                         </tr>  
  40.                                         <tr*ngIf="activeRow==StudentMasters.stdID">  
  41.                                             <tdcolspan="6" style="border: solid1px#659EC7; padding: 5px;table-layout:fixed;">  
  42.                                                 <tableclass='table' style="background-color:#ECF3F4; border:2px#6D7B8D; padding:5px;width:99%;table-layout:fixed;" cellpadding="2" cellspacing="2" *ngIf="studentdetails">  
  43.                                                     <trstyle="height: 30px; background-color:#659EC7 ; color:#FFFFFF ;border: solid1px#659EC7;">  
  44.                                                         <tdwidth="100" align="center">  
  45.                                                             <Strong>Student Detail --></Strong>  
  46.                                                             </td>  
  47.                                                             <tdwidth="240" align="center">Major</td>  
  48.                                                                 <tdwidth="240" align="center">Year</td>  
  49.                                                                     <tdwidth="120" align="center">Term</td>  
  50.                                                                         <tdwidth="340" align="center">Grade</td>  
  51.                                                                             </tr>  
  52.                                                                             <tbody*ngFor="let stddetails of studentdetails">  
  53.                                                                                 <tr>  
  54.                                                                                     <tdwidth="100" align="center">  
  55.                                                                                         </td>  
  56.                                                                                         <tdwidth="240" align="center">{{stddetails.major}}</td>  
  57.                                                                                             <tdwidth="240" align="center">{{stddetails.year}}</td>  
  58.                                                                                                 <tdwidth="120" align="center">{{stddetails.term}}</td>  
  59.                                                                                                     <tdwidth="340" align="center">{{stddetails.grade}}</td>  
  60.                                                                                 </tr>  
  61.                                                                                 </tbody>  
  62.                                                                                 </table>  
  63.                                                                                 </td>  
  64.                                                                                 </tr>  
  65.                                                                                 </tbody>  
  66.                                                                                 </table>  
Step 7 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 navmenumenu. Write the below code to add our navigation menu link for students. Here, we have removed the existing "Count and Fetch" menu.
  1. <li[routerLinkActive]="['link-active']">  
  2.     <a[routerLink]="['/students']">  
  3.         <spanclass='glyphiconglyphicon-th-list'>  
  4.             </span> Students </a>  
  5.             </li>  
HTML

Step 8 App Module

App Module is the root for all files and we can find the app.module.ts under ClientApp\app to import our students component.
  1. import {  
  2.     studentsComponent  
  3. } from './components/students/students.component';  
  4. Next in @NGModule add studentsComponent  
  5. In routing add our students path.  
  6. The code will be looks like this  
  7. import {  
  8.     NgModule  
  9. } from '@angular/core';  
  10. import {  
  11.     RouterModule  
  12. } from '@angular/router';  
  13. import {  
  14.     UniversalModule  
  15. } from 'angular2-universal';  
  16. import {  
  17.     AppComponent  
  18. } from './components/app/app.component'  
  19. import {  
  20.     NavMenuComponent  
  21. } from './components/navmenu/navmenu.component';  
  22. import {  
  23.     HomeComponent  
  24. } from './components/home/home.component';  
  25. import {  
  26.     FetchDataComponent  
  27. } from './components/fetchdata/fetchdata.component';  
  28. import {  
  29.     CounterComponent  
  30. } from './components/counter/counter.component';  
  31. import {  
  32.     studentsComponent  
  33. } from './components/students/students.component';  
  34. @NgModule({  
  35.     bootstrap: [AppComponent],  
  36.     declarations: [  
  37.         AppComponent,  
  38.         NavMenuComponent,  
  39.         CounterComponent,  
  40.         FetchDataComponent,  
  41.         HomeComponent,  
  42.         studentsComponent  
  43.     ],  
  44.     imports: [  
  45.         UniversalModule, // Must be first import. This automatically imports BrowserModule, HttpModule, and JsonpModule too.  
  46.         RouterModule.forRoot([{  
  47.             path: '',  
  48.             redirectTo: 'home',  
  49.             pathMatch: 'full'  
  50.         }, {  
  51.             path: 'home',  
  52.             component: HomeComponent  
  53.         }, {  
  54.             path: 'counter',  
  55.             component: CounterComponent  
  56.         }, {  
  57.             path: 'fetch-data',  
  58.             component: FetchDataComponent  
  59.         }, {  
  60.             path: 'students',  
  61.             component: studentsComponent  
  62.         }, {  
  63.             path: '**',  
  64.             redirectTo: 'home'  
  65.         }])  
  66.     ]  
  67. })  
  68. exportclassAppModule {}  
Step 9 Build and run the application

Build and run the application. You can see that our Students Master/Detail page will be loaded with all Student, Master, and Details information.

HTML

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 and StudentDetails Tables. Also, don’t forget to change the connection string in “appsettings.json”.

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now