View Model :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplication2.Models
{
public class DOCTORVM
{
public int DID { get; set; }
public string NAME { get; set; }
public string ADDRESS { get; set; }
public string PASSWORD { get; set; }
public string CPASSWORD { get; set; }
public string GENDER { get; set; }
public bool? ISMARRIED { get; set; }
public int? CID { get; set; }
public int? SID { get; set; }
public List<int> HLIST { get; set; }
}
}
Web API :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApplication2.Models;
namespace WebApplication2.Controllers
{
[RoutePrefix("api/Doctorservices")]
public class DoctorservicesController : ApiController
{
[HttpGet]
[Route("Countries")]
public IHttpActionResult Countries()
{
try
{
using (Database1Entities obj = new Models.Database1Entities())
{
return Ok(obj.COUNTRies.ToList());
}
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpGet]
[Route("Hobbies")]
public IHttpActionResult Hobbies()
{
try
{
using (Database1Entities obj = new Models.Database1Entities())
{
return Ok(obj.HOBBies.ToList());
}
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpGet]
[Route("Doctors")]
public IHttpActionResult Doctors()
{
try
{
using (Database1Entities obj = new Models.Database1Entities())
{
return Ok(obj.DOCTORs.ToList());
}
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpGet]
[Route("Doctor/{DID:int}",Name ="doctor")]
public IHttpActionResult Doctor(int DID)
{
try
{
using (Database1Entities obj = new Models.Database1Entities())
{
DOCTORVM vm = obj.DOCTORs.Select(e => new DOCTORVM { DID = e.DID, NAME = e.NAME, ADDRESS = e.ADDRESS, PASSWORD = e.PASSWORD,CPASSWORD=e.PASSWORD , GENDER = e.GENDER, ISMARRIED = e.ISMARRIED, CID = e.CID, SID = e.SID, HLIST = obj.HMAPs.Where(m => m.STID == DID).Select(p => p.HID.Value).ToList() }).SingleOrDefault(n => n.DID == DID);
return Ok(vm);
}
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpGet]
[Route("State/{CID:int}")]
public IHttpActionResult State(int CID)
{
try
{
using (Database1Entities obj = new Models.Database1Entities())
{
return Ok(obj.STATEs.Where(e=>e.CID==CID).ToList());
}
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpPost]
[Route("Save")]
public IHttpActionResult Save(DOCTORVM vm)
{
try
{
using (Database1Entities obj = new Models.Database1Entities())
{
DOCTOR doc = new DOCTOR();
doc.DID = vm.DID;
doc.NAME = vm.NAME;
doc.ADDRESS = vm.ADDRESS;
doc.PASSWORD = vm.CPASSWORD;
doc.GENDER = vm.GENDER;
doc.ISMARRIED = vm.ISMARRIED;
doc.ISMARRIED = vm.ISMARRIED;
doc.CID = vm.CID;
doc.SID = vm.SID;
obj.DOCTORs.Add(doc);
obj.SaveChanges();
obj.HMAPs.AddRange(vm.HLIST.Select(e => new HMAP { HID = e, STID = vm.DID }));
obj.SaveChanges();
return Created(new Uri(Url.Link("doctor", new { DID = vm.DID })),"Data Saved.");
}
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpPut]
[Route("Update/{DID:int}")]
public IHttpActionResult Update([FromUri]int DID,[FromBody]DOCTORVM vm)
{
try
{
using (Database1Entities obj = new Models.Database1Entities())
{
DOCTOR doc = obj.DOCTORs.Find(DID);
doc.NAME = vm.NAME;
doc.ADDRESS = vm.ADDRESS;
doc.GENDER = vm.GENDER;
doc.ISMARRIED = vm.ISMARRIED;
doc.ISMARRIED = vm.ISMARRIED;
doc.CID = vm.CID;
doc.SID = vm.SID;
obj.SaveChanges();
obj.HMAPs.RemoveRange(obj.HMAPs.Where(e => e.STID == DID));
obj.SaveChanges();
obj.HMAPs.AddRange(vm.HLIST.Select(e => new HMAP { HID = e, STID = vm.DID }));
obj.SaveChanges();
return Ok("Data Updated.");
}
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpDelete]
[Route("Delete/{DID:int}")]
public IHttpActionResult Delete([FromUri]int DID)
{
try
{
using (Database1Entities obj = new Models.Database1Entities())
{
DOCTOR doc = obj.DOCTORs.Find(DID);
obj.DOCTORs.Remove(doc);
obj.SaveChanges();
obj.HMAPs.RemoveRange(obj.HMAPs.Where(e => e.STID == DID));
obj.SaveChanges();
return Ok("Data Deleted.");
}
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
}
}
Angularjs View :
<form #frmDoct="ngForm" class="form-horizontal">
<div class="form-group" [class.has-error]="DID.invalid && DID.touched" [class.has-success]="DID.valid">
<label class="control-label col-lg-4">DID</label>
<div class="col-lg-4">
<input type="text" name="DID" [(ngModel)]="DOCTOR.DID" #DID="ngModel" class="form-control" required />
<span class="help-block" *ngIf="DID.invalid && DID.touched">DID should be not blank.</span>
</div>
</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" name="NAME" [(ngModel)]="DOCTOR.NAME" #NAME="ngModel" class="form-control" required />
<span class="help-block" *ngIf="NAME.invalid && NAME.touched">Name should be not blank.</span>
</div>
</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 name="ADDRESS" [(ngModel)]="DOCTOR.ADDRESS" #ADDRESS="ngModel" class="form-control" required ></textarea>
<span class="help-block" *ngIf="ADDRESS.invalid && ADDRESS.touched">Address should be not blank.</span>
</div>
</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" name="PASSWORD" minlength="6" [(ngModel)]="DOCTOR.PASSWORD" #PASSWORD="ngModel" class="form-control" required />
<span class="help-block">
<span *ngIf="PASSWORD.errors?.required && PASSWORD.touched">Password should be not blank.</span>
<span *ngIf="PASSWORD.errors?.minlength && PASSWORD.touched">Password min length is 6.</span>
</span>
</div>
</div>
<div class="form-group" [class.has-error]="CPASSWORD.invalid && CPASSWORD.touched" [class.has-success]="CPASSWORD.valid">
<label class="control-label col-lg-4">CONFIRM PASSWORD</label>
<div class="col-lg-4">
<input type="password" name="CPASSWORD" minlength="6" appCompareValidator="PASSWORD" [(ngModel)]="DOCTOR.CPASSWORD" #CPASSWORD="ngModel" class="form-control" required />
<span class="help-block">
<span *ngIf="CPASSWORD.errors?.required && CPASSWORD.touched">Confirm password should be not blank.</span>
<span *ngIf="CPASSWORD.errors?.minlength && CPASSWORD.touched">Confirm password min length is 6.</span>
<span *ngIf="CPASSWORD.errors?.notEqual && CPASSWORD.touched && !CPASSWORD.errors?.minlength && !CPASSWORD.errors?.required">Password and confirm pasword must be same.</span>
</span>
</div>
</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" name="GENDER" [(ngModel)]="DOCTOR.GENDER" #GENDER="ngModel" value="Male" required />Male
<input type="radio" name="GENDER" [(ngModel)]="DOCTOR.GENDER" #GENDER="ngModel" value="Female" required />Female
<span class="help-block" *ngIf="GENDER.invalid && GENDER.touched">Please select a gender.</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-4">ARE YOU MARRIED ?</label>
<div class="col-lg-4">
<input type="checkbox" name="ISMARRIED" [(ngModel)]="DOCTOR.ISMARRIED" #ISMARRIED="ngModel"/>
</div>
</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 name="CID" (change)="fillddl()" [(ngModel)]="DOCTOR.CID" #CID="ngModel" class="form-control" required >
<option [ngValue]="null">Select</option>
<option *ngFor="let c of listc" [value]="c.CID">{{c.CNAME}}</option>
</select>
<span class="help-block" *ngIf="CID.invalid && CID.touched">Please select a country.</span>
</div>
</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 name="SID" [(ngModel)]="DOCTOR.SID" #SID="ngModel" class="form-control" required>
<option [ngValue]="null">Select</option>
<option *ngFor="let c of lists" [value]="c.SID">{{c.SNAME}}</option>
</select>
<span class="help-block" *ngIf="SID.invalid && SID.touched">Please select a state.</span>
</div>
</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 name="HLIST" multiple [(ngModel)]="DOCTOR.HLIST" #HLIST="ngModel" class="form-control" required>
<option *ngFor="let c of listh" [value]="c.HID">{{c.HNAME}}</option>
</select>
<span class="help-block" *ngIf="HLIST.invalid && HLIST.touched">Please select a hobby.</span>
</div>
</div>
<div class="form-group" >
<label class="control-label col-lg-4"></label>
<div class="col-lg-4">
<input type="button" value="Save" style="width:80px" class="btn btn-primary" (click)="save(frmDoct.invalid)" />
<input type="button" value="Update" style="width:80px" class="btn btn-primary" (click)="update(frmDoct.invalid)" />
<input type="button" value="Reset" style="width:80px" class="btn btn-primary" (click)="reset()" />
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-4"></label>
<div class="col-lg-4">
<table class="table table-bordered table-condensed table-hover table-responsive table-striped">
<thead class="bg bg-primary">
<tr>
<th>DID</th>
<th>NAME</th>
<th>ACTION</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let c of list">
<td>{{c.DID}}</td>
<td>{{c.NAME}}</td>
<td>
<a (click)="edit(c.DID)">Edit</a> |
<a (click)="del(c.DID)">Delete</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</form>
Angularjs Costume Directive :
import { Validator, AbstractControl, NG_VALIDATORS } from '@angular/forms';
import { Directive, Input } from '@angular/core';
@Directive({
selector: '[appCompareValidator]',
providers: [{
provide: NG_VALIDATORS,
useExisting: CompareDirective,
multi: true
}]
})
export class CompareDirective implements Validator {
@Input() appCompareValidator: string;
validate(control: AbstractControl): { [key: string]: any } | null {
const controlToCompare = control.parent.get(this.appCompareValidator);
if (controlToCompare && controlToCompare.value !== control.value) {
return { 'notEqual': true };
}
return null;
}
}
Angularjs Model :
export interface Idoctor {
DID: number;
NAME: string;
ADDRESS: string;
PASSWORD: string;
CPASSWORD: string;
GENDER: string;
ISMARRIED: boolean;
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;
STATUS: boolean;
}
Angularjs Services :
import { Injectable } from '@angular/core';
import { Idoctor, Icountry, Istate, Ihobby } from './doctor.model';
import { Http, Headers, Request, RequestMethod, Response, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class DoctorService {
constructor(private _http: Http) { }
Getc(): Promise<Icountry[]> {
return this._http.get('http://localhost:3592/api/Doctorservices/Countries')
.map((res: Response) => <Icountry[]>res.json())
.toPromise();
}
Geth(): Promise<Ihobby[]> {
return this._http.get('http://localhost:3592/api/Doctorservices/Hobbies')
.map((res: Response) => <Ihobby[]>res.json())
.toPromise();
}
Getd(): Promise<Idoctor[]> {
return this._http.get('http://localhost:3592/api/Doctorservices/Doctors')
.map((res: Response) => <Idoctor[]>res.json())
.toPromise();
}
Get(did: number): Promise<Idoctor> {
return this._http.get('http://localhost:3592/api/Doctorservices/Doctor/' + did)
.map((res: Response) => <Idoctor>res.json())
.toPromise();
}
Gets(cid: number): Promise<Istate[]> {
return this._http.get('http://localhost:3592/api/Doctorservices/State/' + cid)
.map((res: Response) => <Istate[]>res.json())
.toPromise();
}
Save(doc: Idoctor): Promise<string> {
const headerOptions = new Headers({ 'Content-Type': 'application/json', cache: false });
const requestOptions = new RequestOptions({ method: RequestMethod.Post, headers: headerOptions });
return this._http.post('http://localhost:3592/api/Doctorservices/Save', JSON.stringify(doc), requestOptions)
.map((res: Response) => <string>res.json())
.toPromise();
}
Update(doc: Idoctor): Promise<string> {
const headerOptions = new Headers({ 'Content-Type': 'application/json', cache: false });
const requestOptions = new RequestOptions({ method: RequestMethod.Put, headers: headerOptions });
return this._http.put('http://localhost:3592/api/Doctorservices/Update/' + doc.DID, JSON.stringify(doc), requestOptions)
.map((res: Response) => <string>res.json())
.toPromise();
}
Delete(did: number): Promise<string> {
const headerOptions = new Headers({ 'Content-Type': 'application/json', cache: false });
const requestOptions = new RequestOptions({ method: RequestMethod.Delete, headers: headerOptions });
return this._http.delete('http://localhost:3592/api/Doctorservices/Delete/' + did, requestOptions)
.map((res: Response) => <string>res.json())
.toPromise();
}
}
Angularjs Component:
import { Component, OnInit } from '@angular/core';
import { Idoctor, Icountry, Istate, Ihobby } from '../doctors/doctor.model';
import { DoctorService } from './doctor.services';
@Component({
selector: 'app-doctor-create',
templateUrl: './doctor-create.component.html',
styleUrls: ['./doctor-create.component.css']
})
export class DoctorCreateComponent implements OnInit {
DOCTOR: Idoctor;
listc: Icountry[];
lists: Istate[];
listh: Ihobby[];
list: Idoctor[];
constructor(private ds: DoctorService) { }
ngOnInit() {
this.reset();
this.fill();
}
fx(cid: number): void {
this.ds.Gets(cid).then(data => {
if (data == null) {
alert('Service return null value.');
} else {
this.lists = data;
}
});
}
fillddl(): void {
this.fx(this.DOCTOR.CID);
}
reset(): void {
this.DOCTOR = {
DID: null,
NAME: null,
ADDRESS: null,
PASSWORD: null,
CPASSWORD: null,
GENDER: null,
ISMARRIED: true,
CID: null,
SID: null,
HLIST: []
};
this.ds.Getc().then(data => {
if (data == null) {
alert('Service return null value.');
} else {
this.listc = data;
}
});
this.ds.Geth().then(data => {
if (data == null) {
alert('Service return null value.');
} else {
this.listh = data;
}
});
}
fill(): void {
this.ds.Getd().then(data => this.list = data);
}
edit(id: number): void {
this.ds.Get(id).then(data => {
this.fx(data.CID);
this.DOCTOR = data;
});
}
del(id: number): void {
if (confirm('Do you want to delete it ?')) {
this.ds.Delete(id).then(data => {
alert(data);
this.fill();
});
}
}
save(isValid: boolean): void {
if (isValid === false) {
this.ds.Save(this.DOCTOR).then(data => {
alert(data);
this.reset();
this.fill();
});
}
}
update(isValid: boolean): void {
if (isValid === false) {
this.ds.Update(this.DOCTOR).then(data => {
alert(data);
this.reset();
this.fill();
});
}
}
}
No comments:
Post a Comment