WebApi 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 WebApplication14.Models;
namespace WebApplication14.Controllers
{
[RoutePrefix("api/Maa")]
public class MaaController : ApiController
{
[HttpGet]
[Route("Gets")]
public IHttpActionResult Gets()
{
try
{
using (Database1Entities obj = new Database1Entities())
{
return Ok(obj.EMP1.ToList());
}
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
[HttpGet]
[Route("Get/{EID:int}",Name ="Test")]
public IHttpActionResult Get(int EID)
{
try
{
using (Database1Entities obj = new Database1Entities())
{
return Ok(obj.EMP1.Find(EID));
}
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
[HttpPost]
[Route("Save")]
public IHttpActionResult Save(EMP1 emp)
{
try
{
using (Database1Entities obj = new Database1Entities())
{
obj.Entry(emp).State = EntityState.Added;
obj.SaveChanges();
return Created(new Uri(Url.Link("Test", new { EID = emp.EID })),"Data Saved.");
}
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
[HttpPut]
[Route("Update")]
public IHttpActionResult Update(EMP1 emp)
{
try
{
using (Database1Entities obj = new Database1Entities())
{
obj.Entry(emp).State = EntityState.Modified;
obj.SaveChanges();
return Ok("Data Updated.");
}
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
[HttpDelete]
[Route("Delete/{EID:int}")]
public IHttpActionResult Delete(int EID)
{
try
{
using (Database1Entities obj = new Database1Entities())
{
obj.Entry(obj.EMP1.Find(EID)).State = EntityState.Deleted;
obj.SaveChanges();
return Ok("Data Deleted.");
}
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
}
}
Angular Code :
Model :
export class ITAGDIR {
EID: number;
NAME: string;
GENDER: string;
}
Service :
import { Injectable } from '@angular/core';
import {HttpClient, HttpHeaders } from '@angular/common/http';
import { ITAGDIR } from '../tagdir/tagdir.model';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
@Injectable()
export class TagdirServices {
constructor(private _http: HttpClient) {
}
baseUrl = 'http://localhost:50559/api/Maa';
Gets() {
return this._http.get(`${this.baseUrl}/${'Gets'}`)
.catch((err) => {
return Observable.throw(err);
});
}
Get(eid: number) {
return this._http.get(`${this.baseUrl}/${'Get'}/${eid}`)
.catch((err) => {
return Observable.throw(err);
});
}
Save(emp: ITAGDIR) {
return this._http.post(`${this.baseUrl}/${'Save'}`
, JSON.stringify(emp)
, {headers: new HttpHeaders({'Content-Type' : 'application/json'})} )
.catch((err) => {
return Observable.throw(err);
});
}
Update(emp: ITAGDIR) {
return this._http.put(`${this.baseUrl}/${'Update'}`
, JSON.stringify(emp)
, {headers: new HttpHeaders({'Content-Type' : 'application/json'})} )
.catch((err) => {
return Observable.throw(err);
});
}
Delete(eid: number) {
return this._http.delete(`${this.baseUrl}/${'Delete'}/${eid}`
, {headers: new HttpHeaders({'Content-Type' : 'application/json'})})
.catch((err) => {
return Observable.throw(err);
});
}
}
Pipe :
import {Pipe, PipeTransform} from '@angular/core';
@Pipe({
name: 'Tagdir'
})
export class TagdirPipe implements PipeTransform {
transform(value: string, gender: string): string {
if ( gender.toLowerCase() === 'male') {
return 'Mr. ' + value;
} else {
return 'Miss. ' + value;
}
}
}
Create & Update view :
<form class="form-horizontal" [formGroup]="frmPita">
<div class="form-group">
<label class="control-label col-lg-4"></label>
<div class="col-lg-4 alert-danger" *ngIf='errorMessage !== undefined'>
{{errorMessage}}
</div>
</div>
<div class="form-group" [ngClass]="{'has-error':frmPita.get('EID').errors && (frmPita.get('EID').touched || frmPita.get('EID').dirty )}">
<label class="control-label col-lg-4">EID</label>
<div class="col-lg-4">
<input type="text" class="form-control" formControlName="EID" />
</div>
<span class="has-error help-block" *ngIf="frmPita.get('EID').errors && (frmPita.get('EID').touched || frmPita.get('EID').dirty)">
<span *ngIf="frmPita.get('EID').errors.required">
Eid should not be blank.
</span>
</span>
</div>
<div class="form-group" [ngClass]="{'has-error':frmPita.get('NAME').errors && (frmPita.get('NAME').touched || frmPita.get('NAME').dirty )}">
<label class="control-label col-lg-4">NAME</label>
<div class="col-lg-4">
<input type="text" class="form-control" formControlName="NAME" />
</div>
<span class="has-error help-block" *ngIf="frmPita.get('NAME').errors && (frmPita.get('NAME').touched || frmPita.get('NAME').dirty)">
<span *ngIf="frmPita.get('NAME').errors.required">
Name should not be blank.
</span>
</span>
</div>
<div class="form-group" [ngClass]="{'has-error':frmPita.get('GENDER').errors && (frmPita.get('GENDER').touched || frmPita.get('GENDER').dirty)}">
<label class="control-label col-lg-4">GENDER</label>
<div class="col-lg-4">
<input type="radio" formControlName="GENDER" value="Male" />Male
<input type="radio" formControlName="GENDER" value="Female" />Female
</div>
<span class="has-error help-block" *ngIf="frmPita.get('GENDER').errors && (frmPita.get('GENDER').touched || frmPita.get('GENDER').dirty)">
<span *ngIf="frmPita.get('GENDER').errors.required">
Please select a gender.
</span>
</span>
</div>
<div class="form-group">
<label class="control-label col-lg-4"></label>
<div class="col-lg-4">
<input type="button" value="Submit" class="btn btn-primary" style="width:80px" (click)="save(frmPita.invalid)" />
<input type="button" value="Reset" class="btn btn-primary" style="width:80px" (click)="reset(frmPita)" />
<a [routerLink]="['/list']">Back To List</a>
</div>
</div>
</form>
Create & Update Component :
import { Component, OnInit } from '@angular/core';
import { ITAGDIR } from '../tagdir/tagdir.model';
import { FormGroup, FormBuilder, Validators, NgForm } from '@angular/forms';
import { TagdirServices } from '../tagdir/tagdir.service';
import { Router, ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-createtagdir',
templateUrl: './createtagdir.component.html',
styleUrls: ['./createtagdir.component.css']
})
export class CreatetagdirComponent implements OnInit {
constructor(private fb: FormBuilder, private ts: TagdirServices, private ro: Router, private ac: ActivatedRoute) { }
frmPita: FormGroup;
TAGDIR: ITAGDIR;
errorMessage: string;
id: number;
ngOnInit() {
this.CLR();
this.frmPita = this.fb.group({
EID: [null, Validators.required],
NAME: [null, Validators.required],
GENDER: [null, Validators.required]
});
this.id = this.ac.snapshot.params['id'];
if (this.id !== undefined) {
this.ts.Get(this.id).subscribe((data) => {
this.frmPita.setValue({
EID : data.EID,
NAME: data.NAME,
GENDER: data.GENDER
});
}, (err) => {
this.errorMessage = err.message;
});
}
}
CLR(): void {
this.TAGDIR = {
EID: null,
NAME: null,
GENDER: null
};
}
reset(chk: NgForm): void {
this.errorMessage = '';
chk.reset();
}
save(isValid: boolean): void {
this.TAGDIR.EID = this.frmPita.value.EID;
this.TAGDIR.NAME = this.frmPita.value.NAME;
this.TAGDIR.GENDER = this.frmPita.value.GENDER;
if (!isValid) {
if (this.id === undefined) {
this.ts.Save(this.TAGDIR).subscribe((data) => {
alert(data);
this.frmPita.reset();
this.ro.navigate(['/list']);
}, (err) => {
this.errorMessage = err.message;
});
} else {
this.ts.Update(this.TAGDIR).subscribe((data) => {
alert(data);
this.frmPita.reset();
this.ro.navigate(['/list']);
}, (err) => {
this.errorMessage = err.message;
});
}
}
}
}
List View :
<div class="row">
<input type="button" value="Add New" class="btn btn-primary" style="width:80px" [routerLink]="['/create']" />
</div><br />
<div class="row">
<span class="alert-danger" *ngIf='errorMessage !== undefined'>
{{errorMessage}}
</span>
</div>
<div class="row">
<table class="table table-borderedt table-bordered table-condensed table-hover table-responsive table-striped">
<thead class="bg bg-primary">
<tr>
<th>Sl No.</th>
<th>NAME</th>
<th>GENDER</th>
<th>ACTION</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let c of list;let i=index">
<td>{{i+1}}</td>
<td>{{c.NAME|Tagdir:c.GENDER}}</td>
<td>{{c.GENDER}}</td>
<td>
<a [routerLink]="['/create',c.EID]">Edit</a> | <a (click)="del(c.EID)">Delete</a>
</td>
</tr>
</tbody>
</table>
</div>
List Component :
import { Component, OnInit } from '@angular/core';
import { ITAGDIR } from '../tagdir/tagdir.model';
import { TagdirServices } from '../tagdir/tagdir.service';
@Component({
selector: 'app-listtagdir',
templateUrl: './listtagdir.component.html',
styleUrls: ['./listtagdir.component.css']
})
export class ListtagdirComponent implements OnInit {
constructor(private ts: TagdirServices) {
this.fill();
}
list: ITAGDIR[];
errorMessage: string;
ngOnInit() {
}
del(eid: number): void {
if (confirm('Do you want to delete it ?')) {
this.ts.Delete(eid).subscribe((data) => {
alert(data);
this.fill();
}, (err) => {
this.errorMessage = err.message;
});
}
}
fill(): void {
this.ts.Gets().subscribe((data) => {
this.list = data;
}, (err) => {
this.errorMessage = err.message;
});
}
}
No comments:
Post a Comment