Web api Code :
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApplication5.Models;
namespace WebApplication5.Controllers
{
[RoutePrefix("api/Bangaloreservices")]
public class BangaloreservicesController : ApiController
{
[HttpGet]
[Route("Countries")]
public HttpResponseMessage Countries()
{
try
{
using (Database1Entities obj = new Models.Database1Entities())
{
return Request.CreateResponse(HttpStatusCode.OK, obj.COUNTRies.ToList());
}
}
catch(Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
}
}
[HttpGet]
[Route("Sates/{CID:int}")]
public HttpResponseMessage Countries(int CID)
{
try
{
using (Database1Entities obj = new Models.Database1Entities())
{
return Request.CreateResponse(HttpStatusCode.OK, obj.STATEs.Where(e=>e.CID==CID).ToList());
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
}
}
[HttpGet]
[Route("Gets")]
public HttpResponseMessage Gets()
{
try
{
using (Database1Entities obj = new Models.Database1Entities())
{
return Request.CreateResponse(HttpStatusCode.OK , obj.BANGALORs.ToList());
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
}
}
[HttpGet]
[Route("Get/{DID:int}",Name ="BGET")]
public HttpResponseMessage Get(int did)
{
try
{
using (Database1Entities obj = new Models.Database1Entities())
{
BANGALORVM vm = obj.BANGALORs.Select(p => new BANGALORVM { DID=p.DID, NAME=p.NAME }).SingleOrDefault(e=>e.DID==did);
vm.LMANGALOR = obj.MANGALORs.Where(m => m.DID == did).ToList();
return Request.CreateResponse(HttpStatusCode.OK,vm);
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
}
}
[HttpPost]
[Route("Save")]
public HttpResponseMessage Save(BANGALORVM vm)
{
try
{
using (Database1Entities obj = new Models.Database1Entities())
{
BANGALOR bm = new BANGALOR();
bm.DID = vm.DID;
bm.NAME = vm.NAME;
obj.Entry(bm).State = EntityState.Added;
obj.SaveChanges();
obj.MANGALORs.AddRange(vm.LMANGALOR.Select(e => new MANGALOR { NAME = e.NAME, CID = e.CID, DID = vm.DID }));
obj.SaveChanges();
var req= Request.CreateResponse(HttpStatusCode.Created,"Data Saved.");
req.Headers.Location = new Uri(Url.Link("BGET", new { did = vm.DID }));
return req;
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
}
}
[HttpPut]
[Route("Update/{did:int}")]
public HttpResponseMessage Update([FromUri]int did,[FromBody]BANGALORVM vm)
{
try
{
using (Database1Entities obj = new Models.Database1Entities())
{
BANGALOR bm = obj.BANGALORs.Find(did);
bm.NAME = vm.NAME;
obj.Entry(bm).State = EntityState.Modified;
obj.SaveChanges();
obj.MANGALORs.RemoveRange(obj.MANGALORs.Where(e => e.DID == did));
obj.SaveChanges();
obj.MANGALORs.AddRange(vm.LMANGALOR.Select(e => new MANGALOR { NAME = e.NAME, CID = e.CID, DID = vm.DID }));
obj.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK, "Data Updated.");
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
}
}
[HttpDelete]
[Route("Delete/{did:int}")]
public HttpResponseMessage Delete([FromUri]int did)
{
try
{
using (Database1Entities obj = new Models.Database1Entities())
{
BANGALOR bm = obj.BANGALORs.Find(did);
obj.Entry(bm).State = EntityState.Deleted;
obj.SaveChanges();
obj.MANGALORs.RemoveRange(obj.MANGALORs.Where(e => e.DID == did));
obj.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK, "Data Deleted.");
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
}
}
}
}
Angularjs Model :
export interface Ibangalore {
DID: number;
NAME: string;
LMANGALOR: IMANGALOR[];
}
export interface IMANGALOR {
EID: number;
NAME: string;
CID: number;
DID: number;
}
export interface Icountry {
CID: number;
CNAME: string;
}
Angularjs Service :
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Icountry, Ibangalore } from './bangalore.model';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class BangaloreService {
baseUrl = 'http://localhost:2813/api/Bangaloreservices';
constructor(private http: HttpClient) {
}
Getc(): Promise<Icountry[]> {
return this.http.get<Icountry[]>(`${this.baseUrl}/${'Countries'}`)
.toPromise();
}
Save(bm: Ibangalore): Promise<string> {
return this.http.post<string>(`${this.baseUrl}/${'Save'}`
, JSON.stringify(bm)
, { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) })
.toPromise();
}
Gets(): Promise<Ibangalore[]> {
return this.http.get<Ibangalore[]>(`${this.baseUrl}/${'Gets'}`)
.toPromise();
}
Get(id: number): Promise<Ibangalore> {
return this.http.get<Ibangalore>(`${this.baseUrl}/${'Get'}/${id}`)
.toPromise();
}
Update(bm: Ibangalore): Promise<string> {
return this.http.put<string>(`${this.baseUrl}/${'Update'}/${bm.DID}`
, JSON.stringify(bm)
, { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) })
.toPromise();
}
Delete(bid: number): Promise<string> {
return this.http.delete<string>(`${this.baseUrl}/${'Delete'}/${bid}`
, { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) })
.toPromise();
}
}
Angularjs list component :
import { Component, OnInit } from '@angular/core';
import {Router} from '@angular/router';
import { BangaloreService } from './bangalore.service';
import { Ibangalore } from './bangalore.model';
import { Subject } from 'rxjs/Subject';
@Component({
selector: 'app-listbangalore',
templateUrl: './listbangalore.component.html',
styleUrls: ['./listbangalore.component.css']
})
export class ListbangaloreComponent implements OnInit {
list: Ibangalore[];
dtOptions: DataTables.Settings = {};
dtTrigger: Subject<any> = new Subject();
constructor(private ru: Router, private bs: BangaloreService) { }
ngOnInit() {
this.dtOptions = {
pagingType: 'full_numbers',
pageLength: 2
};
this.fill();
}
addNew(): void {
this.ru.navigate(['/create']);
}
fill(): void {
this.bs.Gets().then(data => {
this.list = data;
this.dtTrigger.next();
});
}
del(id: number) {
this.ru.navigate(['/delete', id]);
}
}
Angularjs List View :
<div class="form-group">
<div class="col-lg-8">
<input type="button" class="btn btn-primary" value="Add New" (click)="addNew()" style="width:80px" />
</div>
<label class="control-label col-lg-4"></label>
</div><br><br>
<div class="form-group">
<div class="col-lg-10">
<table datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" class="table table-bordered table-condensed table-hover table-responsive table-striped">
<thead class="bg bg-primary">
<tr>
<th>Sl No.</th>
<th>NAME</th>
<th>ACTION</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let c of list;let i=index">
<td>{{i+1}}</td>
<td>
{{c.NAME}}
</td>
<td>
<a [routerLink]="['/create',c.DID]">Edit</a> |
<a (click)="del(c.DID)">Delete</a>
</td>
</tr>
</tbody>
</table>
</div>
<label class="control-label col-lg-4"></label>
</div>
Angularjs Create Component :
import { Component, OnInit, ViewChild } from '@angular/core';
import { Ibangalore, Icountry, IMANGALOR } from './bangalore.model';
import { BangaloreService } from './bangalore.service';
import { NgForm } from '@angular/forms';
import {Router, ActivatedRoute} from '@angular/router';
import { Subject } from 'rxjs/Subject';
@Component({
selector: 'app-createbangalore',
templateUrl: './createbangalore.component.html',
styleUrls: ['./createbangalore.component.css']
})
export class CreatebangaloreComponent implements OnInit {
@ViewChild('frmDept') public frmD: NgForm;
BM: Ibangalore;
listc: Icountry[];
id: number;
constructor(private bs: BangaloreService, private ru: Router, private ar: ActivatedRoute ) { }
ngOnInit() {
this.CLR();
this.id = this.ar.snapshot.params['id'];
this.bs.Getc().then(data => this.listc = data);
if (this.id !== 0) {
this.bs.Get(this.id).then(data => this.BM = data);
}
}
CLR(): void {
this.BM = {
DID: null,
NAME: null,
LMANGALOR: new Array()
};
this.add();
this.frmD.reset();
this.id = 0;
}
save(): void {
if (this.id !== 0) {
this.bs.Update(this.BM).then(data => {
alert(data);
this.CLR();
this.ru.navigate(['/list']);
});
} else {
this.bs.Save(this.BM).then(data => {
alert(data);
this.CLR();
this.ru.navigate(['/list']);
});
}
}
reset(): void {
this.CLR();
}
add(): void {
this.BM.LMANGALOR.push({EID: null, NAME: null, CID: null, DID: null});
}
sub(m: IMANGALOR): void {
if (this.BM.LMANGALOR.length > 1) {
this.BM.LMANGALOR.splice(this.BM.LMANGALOR.indexOf(m), 1);
}
}
}
Angularjs Create View :
<form class="form-horizontal" #frmDept="ngForm">
<div class="form-group" [class.has-success]="DID.valid" [class.has-error]="DID.invalid && DID.touched">
<label class="control-label col-lg-4">DID</label>
<div class="col-lg-4">
<input type="text" class="form-control" #DID="ngModel" [(ngModel)]="BM.DID" required name="DID" />
</div>
<span class="help-block" *ngIf="DID.invalid && DID.touched">
DID should not be blank.
</span>
</div>
<div class="form-group" [class.has-success]="NAME.valid" [class.has-error]="NAME.invalid && NAME.touched">
<label class="control-label col-lg-4">NAME</label>
<div class="col-lg-4">
<input type="text" class="form-control" #NAME="ngModel" [(ngModel)]="BM.NAME" required name="NAME" />
</div>
<span class="help-block" *ngIf="NAME.invalid && NAME.touched">
Name should not be blank.
</span>
</div>
</form>
<div class="form-group">
<label class="control-label col-lg-4"></label>
<div class="col-lg-6">
<table class="table table-bordered table-condensed table-hover table-responsive table-striped">
<thead class="bg bg-danger">
<tr>
<th>NAME</th>
<th>COUNTRY</th>
<th style="text-align:center"><a style="color:green" (click)="add()">Add</a></th>
</tr>
</thead>
<tbody>
<tr *ngFor="let c of BM.LMANGALOR;let i=index">
<td>
<div class="form-group" [class.has-success]="NAME.valid" [class.has-error]="NAME.invalid && NAME.touched">
<div>
<input type="text" class="form-control" #NAME="ngModel" [(ngModel)]="c.NAME" required name="NAME" />
</div>
<span class="help-block" *ngIf="NAME.invalid && NAME.touched">
Name should not be blank.
</span>
</div>
</td>
<td>
<div class="form-group" [class.has-success]="CID.valid" [class.has-error]="CID.invalid && CID.touched">
<div>
<select class="form-control" #CID="ngModel" [(ngModel)]="c.CID" required name="CID">
<option [ngValue]="null">Select</option>
<option *ngFor="let d of listc" [value]="d.CID">{{d.CNAME}}</option>
</select>
</div>
<span class="help-block" *ngIf="CID.invalid && CID.touched">
Please select a country
</span>
</div>
</td>
<td style="text-align:center"><a style="color:red" (click)="sub(c)">Remove</a></td>
</tr>
</tbody>
</table>
</div>
</div>
<form class="form-horizontal">
<div class="form-group">
<label class="control-label col-lg-4"></label>
<div class="col-lg-4">
<input type="button" class="btn btn-primary" value="Submit" (click)="save()" style="width:80px" />
<input type="button" class="btn btn-primary" value="Reset" (click)="reset()" style="width:80px" /><br><br>
<a [routerLink]="['/list']">Back To List</a>
</div>
</div>
</form>
Angularjs Delete Componet :
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { BangaloreService } from './bangalore.service';
@Component({
selector: 'app-deletebangalore',
templateUrl: './deletebangalore.component.html',
styleUrls: ['./deletebangalore.component.css']
})
export class DeletebangaloreComponent implements OnInit {
id: number;
constructor(private bs: BangaloreService, private ru: Router, private ac: ActivatedRoute) { }
ngOnInit() {
this.id = this.ac.snapshot.params['id'];
}
yes(): void {
this.bs.Delete(this.id).then(data => {
alert(data);
this.ru.navigate(['/list']);
});
}
}
Angularjs Delete View :
<div class="form-group">
<label class="control-label col-lg-12"><h2>Do you want to delete it ?</h2></label>
</div><br><br>
<div class="form-group">
<div class="col-lg-12">
<input type="button" class="btn btn-primary" value="Yes" (click)="yes()" style="width:80px" />
<input type="button" class="btn btn-primary" value="No" [routerLink]="['/list']" style="width:80px" />
</div>
</div>
Angularjs app view :
<div style="padding:5px" class="container">
<ul class="nav nav-tabs">
<li routerLinkActive="Active">
<a routerLink="list">Employee</a>
</li>
<li routerLinkActive="Active">
<a routerLink="list">Department</a>
</li>
</ul>
<br>
<router-outlet></router-outlet>
</div>
Angularjs Router :
const appRoutes: Routes = [
{ path: 'list', component: ListbangaloreComponent },
{ path: 'create/:id', component: CreatebangaloreComponent },
{ path: 'delete/:id', component: DeletebangaloreComponent },
{ path: 'create', component: CreatebangaloreComponent },
{ path: '', redirectTo: '/list', pathMatch: 'full' },
{ path: '**', component: PagenotfoundComponent }
];
No comments:
Post a Comment