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/Authorservices")]
public class AuthorservicesController : 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.BadRequest, ex);
}
}
[HttpGet]
[Route("Hobbies")]
public HttpResponseMessage Hobbies()
{
try
{
using (Database1Entities obj = new Models.Database1Entities())
{
return Request.CreateResponse(HttpStatusCode.OK, obj.HOBBies.ToList());
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
[HttpGet]
[Route("Authors")]
public HttpResponseMessage Authors()
{
try
{
using (Database1Entities obj = new Models.Database1Entities())
{
return Request.CreateResponse(HttpStatusCode.OK, obj.AUTHORs.ToList());
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
[HttpGet]
[Route("Author/{AID:int}",Name ="Get1")]
public HttpResponseMessage Author(int AID)
{
try
{
using (Database1Entities obj = new Models.Database1Entities())
{
AUTHORVM vm = obj.AUTHORs.Where(e => e.AID == AID).Select(p => new AUTHORVM { AID = p.AID, NAME = p.NAME, ADDRESS = p.ADDRESS, PASSWORD = p.PASSWORD, GENDER = p.GENDER, EMAIL = p.EMAIL, SALARY = p.SALARY, DOB = p.DOB, CID = p.CID, SID = p.SID }).SingleOrDefault(m => m.AID == AID);
vm.HLIST = obj.HMAPs.Where(e => e.WID == AID).Select(p => p.HID.Value).ToList();
return Request.CreateResponse(HttpStatusCode.OK, vm);
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
[HttpGet]
[Route("States/{CID:int}")]
public HttpResponseMessage States(int CID)
{
try
{
using (Database1Entities obj = new Models.Database1Entities())
{
return Request.CreateResponse(HttpStatusCode.OK, obj.STATEs.Where(m=>m.CID==CID).ToList());
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
[HttpPost]
[Route("Save")]
public HttpResponseMessage Save(AUTHORVM vm)
{
try
{
using (Database1Entities obj = new Models.Database1Entities())
{
AUTHOR auth = new AUTHOR();
auth.AID = vm.AID;
auth.NAME = vm.NAME;
auth.ADDRESS = vm.ADDRESS;
auth.PASSWORD = vm.PASSWORD;
auth.GENDER = vm.GENDER;
auth.EMAIL = vm.EMAIL;
auth.SALARY = vm.SALARY;
auth.DOB = vm.DOB;
auth.CID = vm.CID;
auth.SID = vm.SID;
obj.Entry(auth).State = EntityState.Added;
obj.SaveChanges();
obj.HMAPs.AddRange(vm.HLIST.Select(p => new HMAP { WID=vm.AID, HID=p }).ToList());
obj.SaveChanges();
var req= Request.CreateResponse(HttpStatusCode.Created, "Data Saved.");
req.Headers.Location = new Uri(Url.Link("Get1", new { AID = vm.AID }));
return req;
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
[HttpPut]
[Route("Update/{AID:int}")]
public HttpResponseMessage Update([FromUri]int AID,[FromBody]AUTHORVM vm)
{
try
{
using (Database1Entities obj = new Models.Database1Entities())
{
AUTHOR auth = obj.AUTHORs.Find(AID);
auth.NAME = vm.NAME;
auth.ADDRESS = vm.ADDRESS;
auth.PASSWORD = vm.PASSWORD;
auth.GENDER = vm.GENDER;
auth.EMAIL = vm.EMAIL;
auth.SALARY = vm.SALARY;
auth.DOB = vm.DOB;
auth.CID = vm.CID;
auth.SID = vm.SID;
obj.Entry(auth).State = EntityState.Modified;
obj.SaveChanges();
obj.HMAPs.RemoveRange(obj.HMAPs.Where(e => e.WID == AID).ToList());
obj.SaveChanges();
obj.HMAPs.AddRange(vm.HLIST.Select(p => new HMAP { WID = vm.AID, HID = p }).ToList());
obj.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK, "Data Updated.");
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
[HttpDelete]
[Route("Delete/{AID:int}")]
public HttpResponseMessage Delete([FromUri]int AID)
{
try
{
using (Database1Entities obj = new Models.Database1Entities())
{
AUTHOR auth = obj.AUTHORs.Find(AID);
obj.Entry(auth).State = EntityState.Deleted;
obj.SaveChanges();
obj.HMAPs.RemoveRange(obj.HMAPs.Where(e => e.WID == AID).ToList());
obj.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK, "Data Deleted.");
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
}
}
Angularjs Code:
<form class="form-horizontal" #frmauthor="ngForm">
<div class="form-group " [class.has-error]="AID.invalid && AID.touched" [class.has-success]="AID.valid" >
<label class="control-label col-lg-4">AID</label>
<div class="col-lg-4">
<input type="text" class="form-control" name="AID" required [(ngModel)]="AUTHOR.AID" #AID="ngModel" />
</div>
<span class="help-block has-error" *ngIf="AID.invalid && AID.touched">
AID should not be blank.
</span>
</div>
<div class="form-group " [class.has-error]="NAME.invalid && NAME.touched" [class.has-success]="NAME.valid">
<label class="control-label col-lg-4">NAME</label>
<div class="col-lg-4">
<input type="text" class="form-control" name="NAME" required [(ngModel)]="AUTHOR.NAME" #NAME="ngModel" />
</div>
<span class="help-block has-error" *ngIf="NAME.invalid && NAME.touched">
Name should not be blank.
</span>
</div>
<div class="form-group " [class.has-error]="ADDRESS.invalid && ADDRESS.touched" [class.has-success]="ADDRESS.valid">
<label class="control-label col-lg-4">ADDRESS</label>
<div class="col-lg-4">
<textarea class="form-control" name="ADDRESS" required [(ngModel)]="AUTHOR.ADDRESS" #ADDRESS="ngModel"></textarea>
</div>
<span class="help-block has-error" *ngIf="ADDRESS.invalid && ADDRESS.touched">
Address should not be blank.
</span>
</div>
<div class="form-group " [class.has-error]="PASSWORD.invalid && PASSWORD.touched" [class.has-success]="PASSWORD.valid">
<label class="control-label col-lg-4">PASSWORD</label>
<div class="col-lg-4">
<input type="password" minlength="6" maxlength="8" class="form-control" name="PASSWORD" required [(ngModel)]="AUTHOR.PASSWORD" #PASSWORD="ngModel" />
</div>
<span class="help-block has-error" *ngIf="PASSWORD.errors?.required && PASSWORD.touched">
Password should not be blank.
</span>
<span class="help-block has-error" *ngIf="PASSWORD.errors?.minlength">
Password min length is 6.
</span>
<span class="help-block has-error" *ngIf="PASSWORD.errors?.maxlength">
Password max length is 8.
</span>
</div>
<div class="form-group " [class.has-error]="GENDER.invalid && GENDER.touched" [class.has-success]="GENDER.valid">
<label class="control-label col-lg-4">GENDER</label>
<div class="col-lg-4">
<input type="radio" value="Male" name="GENDER" required [(ngModel)]="AUTHOR.GENDER" #GENDER="ngModel" />Male
<input type="radio" value="Female" name="GENDER" required [(ngModel)]="AUTHOR.GENDER" #GENDER="ngModel" />Female
</div>
<span class="help-block has-error" *ngIf="GENDER.invalid && GENDER.touched">
Please select a gender.
</span>
</div>
<div class="form-group " [class.has-error]="EMAIL.invalid && EMAIL.touched" [class.has-success]="EMAIL.valid">
<label class="control-label col-lg-4">EMAIL</label>
<div class="col-lg-4">
<input type="text" class="form-control" pattern="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" name="EMAIL" required [(ngModel)]="AUTHOR.EMAIL" #EMAIL="ngModel" />
</div>
<span class="help-block has-error" *ngIf="EMAIL.invalid && EMAIL.touched && EMAIL.errors?.required">
Email should not be blank.
</span>
<span class="help-block has-error" *ngIf="EMAIL.touched && EMAIL.errors?.pattern">
Invalid email id.
</span>
</div>
<div class="form-group " [class.has-error]="SALARY.invalid && SALARY.touched" [class.has-success]="SALARY.valid">
<label class="control-label col-lg-4">SALARY</label>
<div class="col-lg-4">
<input type="text" class="form-control" name="SALARY" required [(ngModel)]="AUTHOR.SALARY" #SALARY="ngModel" />
</div>
<span class="help-block has-error" *ngIf="SALARY.invalid && SALARY.touched">
Salary should not be blank.
</span>
</div>
<div class="form-group " [class.has-error]="DOB.invalid && DOB.touched" [class.has-success]="DOB.valid">
<label class="control-label col-lg-4">DOB</label>
<div class="col-lg-4">
<input type="text" class="form-control" name="DOB" required [(ngModel)]="AUTHOR.DOB" #DOB="ngModel" />
</div>
<span class="help-block has-error" *ngIf="DOB.invalid && DOB.touched">
Dob should not be blank.
</span>
</div>
<div class="form-group " [class.has-error]="CID.invalid && CID.touched" [class.has-success]="CID.valid">
<label class="control-label col-lg-4">COUNTRY</label>
<div class="col-lg-4">
<select class="form-control" name="CID" (change)="fillddl()" required [(ngModel)]="AUTHOR.CID" #CID="ngModel">
<option [ngValue]="null">Select</option>
<option *ngFor="let c of listc" [value]="c.CID" >{{c.CNAME}}</option>
</select>
</div>
<span class="help-block has-error" *ngIf="CID.invalid && CID.touched">
Please select a country.
</span>
</div>
<div class="form-group " [class.has-error]="SID.invalid && SID.touched" [class.has-success]="SID.valid">
<label class="control-label col-lg-4">STATE</label>
<div class="col-lg-4">
<select class="form-control" name="SID" required [(ngModel)]="AUTHOR.SID" #SID="ngModel">
<option [ngValue]="null">Select</option>
<option *ngFor="let c of lists" [value]="c.SID">{{c.SNAME}}</option>
</select>
</div>
<span class="help-block has-error" *ngIf="SID.invalid && SID.touched">
Please select a country.
</span>
</div>
<div class="form-group " [class.has-error]="HLIST.invalid && HLIST.touched" [class.has-success]="HLIST.valid">
<label class="control-label col-lg-4">HOBBY</label>
<div class="col-lg-4">
<select class="form-control" multiple name="HLIST" required [(ngModel)]="AUTHOR.HLIST" #HLIST="ngModel">
<option *ngFor="let c of listh" [value]="c.HID">{{c.HNAME}}</option>
</select>
</div>
<span class="help-block has-error" *ngIf="HLIST.invalid && HLIST.touched">
Please select a hobby.
</span>
</div>
<div class="form-group">
<label class="control-label col-lg-4"></label>
<div class="col-lg-4">
<input type="button" value="Save" class="btn btn-primary" style="width:80px" (click)="save(frmauthor.valid)" />
<input type="button" value="Update" class="btn btn-primary" style="width:80px" (click)="update(frmauthor.valid)" />
<input type="button" value="Reset" class="btn btn-primary" style="width:80px" (click)="reset(frmauthor)" />
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-4"></label>
<div class="col-lg-8">
<table 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>ADDRESS</th>
<th>GENDER</th>
<th>SALARY</th>
<th>DOB</th>
<th>ACTION</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let c of list;let i=index">
<td>{{i+1|percent}}</td>
<td>{{c.NAME|CustomPipe:c.GENDER}}</td>
<td>{{c.ADDRESS|lowercase}}</td>
<td>{{c.GENDER|uppercase}}</td>
<td>{{c.SALARY|number:'.3'}}</td>
<td>{{c.DOB|date:'dd-MMM-yyyy'}}</td>
<td>
<a (click)="edit(c.AID)">Edit</a> | <a (click)="del(c.AID)">Delete</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</form>
Angular Model:
export interface Iauthor {
AID: number;
NAME: string;
ADDRESS: string;
PASSWORD: string;
GENDER: string;
EMAIL: string;
SALARY: number;
DOB: Date;
CID: number;
SID: number;
HLIST: number[];
}
export interface Icountry {
CID: number;
CNAME: string;
}
export interface Istate {
SID: number;
SNAME: string;
CID: number;
}
export interface Ihobby {
HID: number;
HNAME: string;
}
Angularjs Services :
import { Injectable } from '@angular/core';
import { NgForm } from '@angular/forms';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Iauthor, Icountry, Istate, Ihobby } from '../author/author.model';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class AuthorServices {
baseUrl = 'http://localhost:2813/api/Authorservices';
constructor(private _http: HttpClient) {
}
Getc(): Promise<Icountry[]> {
return this._http.get<Icountry[]>(`${this.baseUrl}/${'Countries'}`)
.toPromise();
}
Geth(): Promise<Ihobby[]> {
return this._http.get<Ihobby[]>(`${this.baseUrl}/${'Hobbies'}`)
.toPromise();
}
Geta(): Promise<Iauthor[]> {
return this._http.get<Iauthor[]>(`${this.baseUrl}/${'Authors'}`)
.toPromise();
}
Get(AID: number): Promise<Iauthor> {
return this._http.get<Iauthor>(`${this.baseUrl}/${'Author'}/${AID}`)
.toPromise();
}
Gets(CID: number): Promise<Istate[]> {
return this._http.get<Istate[]>(`${this.baseUrl}/${'States'}/${CID}`)
.toPromise();
}
Save(author: Iauthor): Promise<string> {
return this._http.post<string>(`${this.baseUrl}/${'Save'}`
, JSON.stringify(author)
, {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
})
.toPromise();
}
Update(author: Iauthor): Promise<string> {
return this._http.put<string>(`${this.baseUrl}/${'Update'}/${author.AID}`
, JSON.stringify(author)
, {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
})
.toPromise();
}
Delete(aid: number): Promise<string> {
return this._http.delete<string>(`${this.baseUrl}/${'Delete'}/${aid}`
, {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
})
.toPromise();
}
}
Angular js Custom Pipe code :
import {Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'CustomPipe'})
export class BookPipe implements PipeTransform {
transform(value: string, gender: string): string {
if (gender.toLowerCase() === 'male') {
return 'Mr. ' + value;
} else {
return 'Miss. ' + value;
}
}
}
Angular js Componet Code:
import { Component, OnInit, ViewChild } from '@angular/core';
import { Iauthor, Icountry, Istate, Ihobby } from '../author/author.model';
import { AuthorServices } from '../author/author.services';
import { NgForm } from '@angular/forms';
@Component({
selector: 'app-create',
templateUrl: './create.component.html',
styleUrls: ['./create.component.css']
})
export class CreateComponent implements OnInit {
@ViewChild('frmauthor') private frmAuthor: NgForm;
AUTHOR: Iauthor;
listc: Icountry[];
lists: Istate[];
listh: Ihobby[];
list: Iauthor[];
constructor(private ahs: AuthorServices) { }
ngOnInit() {
this.CLR();
this.ahs.Getc().then(data => this.listc = data);
this.ahs.Geth().then(data => this.listh = data);
this.fill();
}
del(aid: number): void {
if (confirm('Do you want to delete it ?')) {
this.ahs.Delete(aid).then(data => {
alert(data);
this.fill();
});
}
}
edit(aid: number): void {
this.ahs.Get(aid).then(data => {
this.fx(data.CID);
this.AUTHOR = data;
});
}
reset(fr: NgForm): void {
fr.reset();
}
fill(): void {
this.ahs.Geta().then(data => this.list = data);
}
fillddl(): void {
this.fx(this.AUTHOR.CID);
}
fx(cid: number): void {
this.ahs.Gets(cid).then(data => this.lists = data);
}
update(isValid): void {
if (isValid) {
this.ahs.Update(this.AUTHOR).then(data => {
alert(data);
this.CLR();
this.fill();
});
}
}
save(isValid): void {
if (isValid) {
this.ahs.Save(this.AUTHOR).then(data => {
alert(data);
this.CLR();
this.fill();
});
}
}
CLR(): void {
this.frmAuthor.reset();
this.AUTHOR = {
AID: null,
NAME: null,
ADDRESS: null,
PASSWORD: null,
GENDER: null,
EMAIL: null,
SALARY: null,
DOB: null,
CID: null,
SID: null,
HLIST: []
};
}
}
No comments:
Post a Comment