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.
- First, download and install Visual Studio 2015 with Update 3 from this link.
- 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.
- Download and install .NET Core 1.0.1
- Download and install TypeScript 2.0
- Download and install Node.js v4.0 or above. I have installed V6.9.1
- Download 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.
- USEMASTER
- GO
- --1) Check
- --
- for the Database Exists.If the database is exist then drop and create new DB
- IFEXISTS(SELECT[name] FROMsys.databasesWHERE[name] = 'StudentsDB')
- DROPDATABASEStudentsDB
- GO
- --CREATEDATABASEStudentsDB
- GO
- USEStudentsDB
- GO
- --1)
- IFEXISTS(SELECT[name] FROMsys.tablesWHERE[name] = 'StudentMasters')
- DROPTABLEStudentMasters
- GO
- CREATETABLE[dbo].[StudentMasters](
- [StdID] INTIDENTITYPRIMARYKEY, [StdName][varchar](100) NOTNULL, [Email][varchar](100) NOTNULL, [Phone][varchar](20) NOTNULL, [Address][varchar](200) NOTNULL)
- --insert sample data to Student Master table
- INSERTINTO[StudentMasters]([StdName], [Email], [Phone], [Address])
- VALUES('Shanu', '[email protected]', '01030550007', 'Madurai,India')
- INSERTINTO[StudentMasters]([StdName], [Email], [Phone], [Address])
- VALUES('Afraz', '[email protected]', '01030550006', 'Madurai,India')
- INSERTINTO[StudentMasters]([StdName], [Email], [Phone], [Address])
- VALUES('Afreen', '[email protected]', '01030550005', 'Madurai,India')
- select * from[StudentMasters]
- IFEXISTS(SELECT[name] FROMsys.tablesWHERE[name] = 'StudentDetails')
- DROPTABLEStudentDetails
- GO
- CREATETABLE[dbo].[StudentDetails](
- [StdDtlID] INTIDENTITYPRIMARYKEY, [StdID] INT, [Major][varchar](100) NOTNULL, [Year][varchar](30) NOTNULL, [Term][varchar](30) NOTNULL, [Grade][varchar](10) NOTNULL)
- INSERTINTO[StudentDetails]([StdID], [Major], [Year], [Term], [Grade])
- VALUES(1, 'Computer Science', 'FirstYear', 'FirstTerm', 'A')
- INSERTINTO[StudentDetails]([StdID], [Major], [Year], [Term], [Grade])
- VALUES(1, 'Computer Science', 'FirstYear', 'SecondTerm', 'B')
- INSERTINTO[StudentDetails]([StdID], [Major], [Year], [Term], [Grade])
- VALUES(1, 'Computer Science', 'SecondYear', 'FirstTerm', 'C')
- INSERTINTO[StudentDetails]([StdID], [Major], [Year], [Term], [Grade])
- VALUES(2, 'Computer Engineer', 'ThirdYear', 'FirstTerm', 'A')
- INSERTINTO[StudentDetails]([StdID], [Major], [Year], [Term], [Grade])
- VALUES(2, 'Computer Engineer', 'ThirdYear', 'SecondTerm', 'A')
- INSERTINTO[StudentDetails]([StdID], [Major], [Year], [Term], [Grade])
- VALUES(3, 'English', 'First Year', 'FirstTerm', 'C')
- INSERTINTO[StudentDetails]([StdID], [Major], [Year], [Term], [Grade])
- VALUES(13, 'Economics', 'First Year', 'FirstTerm', 'A')
- 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.
After creating ASP.NET Core and Angular 2 applications, wait for a few seconds. You will see that all the dependencies are automatically restoring.
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.
- "Microsoft.EntityFrameworkCore.SqlServer": "1.0.1", "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"
When we save the project.json file, we can see the Reference has been restored.
After few seconds, we can see Entity Framework package has been restored and all references have been added.
Adding Connection String
To add the connection string with our SQL connection, open the “appsettings.json” file. Yes, this is a JSON file and this file looks like below image by default.
In this appsettings.json file, add our connection string.
- "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.
Next, we create a folder named “Data” to create our model and DBContext class.
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".
Now, in this class, we first create property variable, then add studentMaster. We will be using this in our WEB API Controller.
- using System;
- usingSystem.Collections.Generic;
- usingSystem.Linq;
- usingSystem.Threading.Tasks;
- usingSystem.ComponentModel.DataAnnotations;
- namespace Angular2ASPCORE.Data {
- publicclassStudentMasters {
- [Key]
- publicintStdID {
- get;
- set;
- }
- [Required]
- [Display(Name = "Name")]
- publicstringStdName {
- get;
- set;
- }
- [Required]
- [Display(Name = "Email")]
- publicstring Email {
- get;
- set;
- }
- [Required]
- [Display(Name = "Phone")]
- publicstring Phone {
- get;
- set;
- }
- publicstring Address {
- get;
- set;
- }
- }
- }
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.
In this class, we first create property variable, then add StudentDetails. We will be using this in our Web API Controller.
- publicclassStudentDetails {
- [Key]
- publicintStdDtlID {
- get;
- set;
- }
- [Required]
- [Display(Name = "StudentID")]
- publicintStdID {
- get;
- set;
- }
- [Required]
- [Display(Name = "Major")]
- publicstring Major {
- get;
- set;
- }
- [Required]
- [Display(Name = "Year")]
- publicstring Year {
- get;
- set;
- }
- [Required]
- [Display(Name = "Term")]
- publicstring Term {
- get;
- set;
- }
- publicstring Grade {
- get;
- set;
- }
- }
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.
In this class, we inherit DbContext and created Dbset for our studentMasters and StudentDetails table.
- using System;
- usingSystem.Collections.Generic;
- usingSystem.Linq;
- usingSystem.Threading.Tasks;
- usingMicrosoft.EntityFrameworkCore;
- namespace Angular2ASPCORE.Data {
- publicclassstudentContext: DbContext {
- publicstudentContext(DbContextOptions < studentContext > options): base(options) {}
- publicstudentContext() {}
- publicDbSet < StudentMasters > StudentMasters {
- get;
- set;
- }
- publicDbSet < StudentDetails > StudentDetails {
- 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.
-
- 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".
Click ASP.NET in right side > Click Web API Controller Class. Enter the name as “StudentMastersAPI.cs” and click "Add".
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.
- [Produces("application/json")]
- [Route("api/StudentMastersAPI")]
- publicclassStudentMastersAPI: Controller {
- privatereadonlystudentContext _context;
- publicStudentMastersAPI(studentContext context) {
- _context = context;
- }
-
-
- [HttpGet]
- [Route("Student")]
- publicIEnumerable < StudentMasters > GetStudentMasters() {
- return _context.StudentMasters;
- }
-
-
- [HttpGet]
- [Route("Details")]
- publicIEnumerable < StudentDetails > GetStudentDetails() {
- return _context.StudentDetails;
- }
-
-
- [HttpGet]
- [Route("Details/{id}")]
- publicIEnumerable < StudentDetails > GetStudentDetails(int id) {
- return _context.StudentDetails.Where(i => i.StdID == id).ToList();
- }
- }
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.
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
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.
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.
In students.component.ts file, we have three parts -
- import part
- component part
- 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.
- import {
- Component
- } from '@angular/core';
- import {
- Http
- } from "@angular/http";
- @Component({
- selector: 'students',
- template: require('./students.component.html')
- })
- exportclassstudentsComponent {
- public student: StudentMasters[] = [];
- publicstudentdetails: StudentDetails[] = [];
- myName: string;
- activeRow: string = "0";
- constructor(public http: Http) {
- this.myName = "Shanu";
- this.getStudentMasterData();
- }
- getStudentMasterData() {
- this.http.get('/api/StudentMastersAPI/Student').subscribe(result => {
- this.student = result.json();
- });
- }
- getStudentsDetails(StudID) {
- this.http.get('/api/StudentMastersAPI/Details/' + StudID).subscribe(result => {
- this.studentdetails = result.json();
- });
- this.activeRow = StudID;
- }
- }
-
- exportinterfaceStudentMasters {
- stdID: number;
- stdName: string;
- email: string;
- phone: string;
- address: string;
- }
-
- exportinterfaceStudentDetails {
- StdDtlID: number;
- stdID: number;
- Major: string;
- Year: string;
- Term: string;
- Grade: string;
- }
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".
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.
- <h1>Angular 2 with ASP.NET Core Template Pack, WEB API and EF 1.0.1 </h1>
- <hr/>
- <h2>My Name is : {{myName}}</h2>
- <hr/>
- <h1>Students Details :</h1>
- <p*ngIf="!student"><em>Loading Student Details please Wait ! ...</em></p>
- <!--<pre>{{studentdetails|json}}</pre>-->
- <tableclass='table' style="background-color:#FFFFFF; border:2px#6D7B8D; padding:5px;width:99%;table-layout:fixed;" cellpadding="2" cellspacing="2" *ngIf="student">
- <trstyle="height: 30px; background-color:#336699 ; color:#FFFFFF ;border: solid1px#659EC7;">
- <tdwidth="80" align="center">
- </td>
- <tdwidth="80" align="center">Student ID</td>
- <tdwidth="240" align="center">Student Name</td>
- <tdwidth="240" align="center">Email</td>
- <tdwidth="120" align="center">Phone</td>
- <tdwidth="340" align="center">Address</td>
- </tr>
- <tbody*ngFor="let StudentMasters of student">
- <tr>
- <tdalign="center" style="border: solid1px#659EC7; padding: 5px;table-layout:fixed;">
- <button(click)=getStudentsDetails(StudentMasters.stdID)style="background-color:#334668;color:#FFFFFF;font-size:large;width:80px;
- border-color:#a2aabe;border-style:dashed;border-width:2px;"> Detail </button>
- </td>
- <tdalign="center" style="border: solid1px#659EC7; padding: 5px;table-layout:fixed;">
- <spanstyle="color:#9F000F">{{StudentMasters.stdID}}</span>
- </td>
- <tdstyle="border: solid1px#659EC7; padding: 5px;table-layout:fixed;">
- <spanstyle="color:#9F000F">{{StudentMasters.stdName}}</span>
- </td>
- <tdstyle="border: solid1px#659EC7; padding: 5px;table-layout:fixed;">
- <spanstyle="color:#9F000F">{{StudentMasters.email}}</span>
- </td>
- <tdalign="center" style="border: solid1px#659EC7; padding: 5px;table-layout:fixed;">
- <spanstyle="color:#9F000F">{{StudentMasters.phone}}</span>
- </td>
- <tdstyle="border: solid1px#659EC7; padding: 5px;table-layout:fixed;">
- <spanstyle="color:#9F000F">{{StudentMasters.address}}</span>
- </td>
- </tr>
- <tr*ngIf="activeRow==StudentMasters.stdID">
- <tdcolspan="6" style="border: solid1px#659EC7; padding: 5px;table-layout:fixed;">
- <tableclass='table' style="background-color:#ECF3F4; border:2px#6D7B8D; padding:5px;width:99%;table-layout:fixed;" cellpadding="2" cellspacing="2" *ngIf="studentdetails">
- <trstyle="height: 30px; background-color:#659EC7 ; color:#FFFFFF ;border: solid1px#659EC7;">
- <tdwidth="100" align="center">
- <Strong>Student Detail --></Strong>
- </td>
- <tdwidth="240" align="center">Major</td>
- <tdwidth="240" align="center">Year</td>
- <tdwidth="120" align="center">Term</td>
- <tdwidth="340" align="center">Grade</td>
- </tr>
- <tbody*ngFor="let stddetails of studentdetails">
- <tr>
- <tdwidth="100" align="center">
- </td>
- <tdwidth="240" align="center">{{stddetails.major}}</td>
- <tdwidth="240" align="center">{{stddetails.year}}</td>
- <tdwidth="120" align="center">{{stddetails.term}}</td>
- <tdwidth="340" align="center">{{stddetails.grade}}</td>
- </tr>
- </tbody>
- </table>
- </td>
- </tr>
- </tbody>
- </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.
- <li[routerLinkActive]="['link-active']">
- <a[routerLink]="['/students']">
- <spanclass='glyphiconglyphicon-th-list'>
- </span> Students </a>
- </li>
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.
- 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
- import {
- NgModule
- } from '@angular/core';
- import {
- RouterModule
- } from '@angular/router';
- 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,
- 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'
- }])
- ]
- })
- 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.
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”.