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.
Note: Kindly read our previous articles which deeply explains about Getting Started with ASP.NET Core Template Pack
In this articles let’s see:
This article will explain in detail about how to create a Master/Detail Table and bind the Master related details in an 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 student’s exam final result for displaying Student Major, Studying Year with Term and Grade details.
Here in the below image we can see when the user clicked on the Student ID “2”. Then we can see next the details grid was being displayed to show student results in detail by Major, Year, Term and Grade.
Here we display the student details by each Student Id.
Make sure you have installed all the prerequisites in your computer. If not, then download and install all of them, one by one.
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. Here we have used SQL Server 2014. Return to Top
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
] =
'StudentsDB'
)
DROP
DATABASE
StudentsDB
--CREATEDATABASEStudentsDB
USE StudentsDB
--1) //////////// StudentMasters
sys.tables
'StudentMasters'
TABLE
StudentMasters
CREATE
[dbo].[StudentMasters](
[StdID]
INT
IDENTITY
PRIMARY
KEY
,
[StdName][
varchar
](100)
NOT
NULL
[Email][
[Phone][
](20)
[Address][
](200)
--insert sample data to Student Master table
INSERT
INTO
[StudentMasters]([StdName], [Email], [Phone], [Address])
VALUES
(
'Shanu'
'syedshanumcain@gmail.com'
'01030550007'
'Madurai,India'
'Afraz'
'Afraz@afrazmail.com'
'01030550006'
'Afreen'
'Afreen@afreenmail.com'
'01030550005'
select
*
from
[StudentMasters]
'StudentDetails'
StudentDetails
[dbo].[StudentDetails](
[StdDtlID]
[Major][
Year
][
](30)
[Term][
[Grade][
](10)
[StudentDetails]([StdID], [Major], [
], [Term],[Grade])
(1,
'Computer Science'
'First Year'
'First Term'
'A'
'Second Term'
'B'
'Second Year'
'C'
(2,
'Computer Engineer'
'Third Year'
(3,
'English'
(13,
'Economics'
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
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 it.
Note: Here we have used EF version 1.0.1. Return to Top
"Microsoft.EntityFrameworkCore.SqlServer": "1.0.1",
"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"
To add the connection string with our SQL connection, open the “appsettings.json” file. Yes, this is the JSON file and this file looks like the below image by default. Return to Top
"ConnectionStrings": {
"DefaultConnection": "Server=YOURDBSERVER;Database=StudentsDB;user id=SQLID;password=SQLPWD;Trusted_Connection=True;MultipleActiveResultSets=true;"
},
Next step is we create a folder named “Data” to create our model and DBContext class. Return to Top
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 StudentMasters and click Add. Return to Top
using
System;
System.Collections.Generic;
System.Linq;
System.Threading.Tasks;
System.ComponentModel.DataAnnotations;
namespace
Angular2ASPCORE.Data
{
public
class
[Key]
int
StdID {
get
;
set
; }
[Required]
[Display(Name =
"Name"
)]
string
StdName {
"Email"
Email {
"Phone"
Phone {
Address {
}
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. Return to Top
StdDtlID {
"StudentID"
"Major"
Major {
"Year"
Year {
"Term"
Term {
Grade {
DBContext is Entity Framework Class for establishing a connection to a 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. Return to Top In this class we inherit DbContext and created Dbset for our studentMasters and StudentDetails table.
Microsoft.EntityFrameworkCore;
studentContext : DbContext
studentContext(DbContextOptions<studentContext> options)
:
base
(options) { }
studentContext() { }
DbSet<StudentMasters> StudentMasters {
DbSet<StudentDetails> StudentDetails {
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. Return to Top
// Add Entity framework .
services.AddDbContext<studentContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString(
"DefaultConnection"
)));
To create our WEB API Controller, right-click Controllers folder. Click Add and click New Item.
In this we are using only the Get method to get all the students result from the database and bind the final result using Angular2 to HTML file.
Here in this Web API we get both Student Master, Student Details and Student Details load by condition student ID. Return to Top
[Produces(
"application/json"
[Route(
"api/StudentMastersAPI"
StudentMastersAPI : Controller
private
readonly
studentContext _context;
StudentMastersAPI(studentContext context)
_context = context;
// GET: api/values
// For Student Master
[HttpGet]
"Student"
IEnumerable<StudentMasters> GetStudentMasters()
return
_context.StudentMasters;
// For Student Detail
"Details"
IEnumerable<StudentDetails> GetStudentDetails()
_context.StudentDetails;
// For Student Detail with studentid to load by student ID
// GET api/values/5
"Details/{id}"
IEnumerable<StudentDetails> GetStudentDetails(
id)
_context.StudentDetails.Where(i => i.StdID == id).ToList();
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
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. Return to Top
Right-click on Students folder and click on add new Item. Select Client-side from the left side and select TypeScript File. Name the file as “students.component.ts” and click Add.
Return to Top In students.component.ts file we have three parts. First is the:
In component, we have a selector 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. 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. Here we get first all the Student Master data from Web API to bind in our HTML page. We have created one more function named “getStudentsDetails” to this function 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'
})
export class studentsComponent {
public student: StudentMasters[] = [];
public studentdetails: StudentDetails[] = [];
myName: string;
activeRow: string =
"0"
constructor(public http: Http) {
this
.myName =
"Shanu"
.getStudentMasterData();
getStudentMasterData() {
.http.get(
'/api/StudentMastersAPI/Student'
).subscribe(result => {
.student = result.json();
});
getStudentsDetails(StudID) {
'/api/StudentMastersAPI/Details/'
+ StudID).subscribe(result => {
.studentdetails = result.json();
.activeRow = StudID;
//// For Student Master
export interface StudentMasters {
stdID: number;
stdName: string;
email: string;
phone: string;
address: string;
// For Student Details
export interface StudentDetails {
StdDtlID: number;
Major: string;
Year: string;
Term: string;
Grade: string;
Right-click on students folder and click on add new Item. Select Client-side from left-side and select HTML File. Name the file as “students.component.html” and click Add. Return to Top
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.
In the Detail Button, click we load the Student Details for selected Student 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 </
>
hr
/>
h2
>My Name is : {{myName}}</
>Students Details :</
p
ngIf
=
"!student"
><
em
>Loading Student Details please Wait ! ...</
></
<!--<pre>{{ studentdetails | json }}</pre>-->
table
'table'
style
"background-color:#FFFFFF; border:2px #6D7B8D; padding:5px;width:99%;table-layout:fixed;"
cellpadding
"2"
cellspacing
"student"
tr
"height: 30px; background-color:#336699 ; color:#FFFFFF ;border: solid 1px #659EC7;"
td
width
"80"
align
"center"
>Student ID</
"240"
>Student Name</
>Email</
"120"
>Phone</
"340"
>Address</
</
tbody
ngFor
"let StudentMasters of student"
"border: solid 1px #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
span
"color:#9F000F"
>{{StudentMasters.stdID}}</
"left"
>{{StudentMasters.stdName}}</
>{{StudentMasters.email}}</
>{{StudentMasters.phone}}</
>{{StudentMasters.address}}</
"activeRow==StudentMasters.stdID"
colspan
"6"
"background-color:#ECF3F4; border:2px #6D7B8D; padding:5px;width:99%;table-layout:fixed;"
"studentdetails"
"height: 30px; background-color:#659EC7 ; color:#FFFFFF ;border: solid 1px #659EC7;"
"100"
Strong
>Student Detail --></
> </
>Major</
>Year</
>Term</
>Grade</
"let stddetails of studentdetails"
>{{stddetails.major}}</
>{{stddetails.year}}</
>{{stddetails.term}}</
>{{stddetails.grade}} </
We can add our newly created student details menu in an 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. Here we have removed the existing Count and Fetch menu. Return to Top
li
[routerLinkActive]="['link-active']">
a
[routerLink]="['/students']">
'glyphicon glyphicon-th-list'
> Students
App Module is the root for all files and we can find the app.module.ts under ClientApp\app, and import our students component. App Module is root for all file and we can find the app.module.ts under ClientApp\ app.Import our students component.
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, // 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 {
Build and run the application and you can see our Students Master/Detail page will be loaded with all Student Master and Detail information. Return to Top