SlideShare ist ein Scribd-Unternehmen logo
1 von 10
Downloaden Sie, um offline zu lesen
Creating Asp.net Web API and
consuming it through HTML Clients
– Part II
Howdy Readers,
Consuming web API through HTML clients
Welcome to our blog ! In our previous post we have seen how to create ASP.NET Web API. If you
aren’t still comfortable in creating Web API then I would suggest you to read our post for creating
Web API.
Today, we will be focusing on consuming web API through HTML clients. Trust me guys, it’s very
easy to consume web API and we will do that using JQuery. If you are unfamiliar with JQuery then
please refer w3 schools for getting some basic idea about it. Latest version of Jquery can be
downloaded from here.
Modify the default file “index.cshtml” in the View/Home folder with the following Markup to provide
a GUI for Displaying Products and their different actions.
<!DOCTYPE html>
<html lang="en">
<body>
<header>
<script type="text/javascript" src="../../Scripts/jquery-1.8.2.js"></script>
</header>
<div id="body">
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h1>Welcome to ASP.NET Web API | Demo by <a href="http://dipendra
shekhawat.com" target="_blank">Dipendra Shekhawat</a></h1>
</hgroup>
</div>
</section>
<section class="content-wrapper main-content clear-fix">
<div>
<h4>Product List</h4>
<input type="button" value="View All Products" onclick="GetAllProduct
s();" />
<ul id="ProductList" />
</div>
<div>
<h4>Search by ID</h4>
<input type="text" id="searchProductID" size="5" />
<input type="button" value="Search" onclick="FindProduct();" />
<p id="prod" />
</div>
<div>
<h4>Delete Product by ID</h4>
<input type="text" id="delProductID" size="5" />
<input type="button" value="Delete" onclick="DeleteProduct();" />
</div>
<div>
<h4>Add Product </h4>
<table>
<tr>
<td>Name</td>
<td><input type="text" id="Name" /></td>
</tr>
<tr>
<td>Type</td>
<td><input type="text" id="Type" /></td>
</tr>
<tr>
<td>Description</td>
<td><input type="text" id="Description" /></td>
</tr>
<tr>
<td>Price</td>
<td><input type="text" id="Price" /></td>
</tr>
<tr>
<td colspan="3" align="center">
<input type="button" value="Add" onclick="AddProduct();
" /></td>
</tr>
</table>
</div>
</section>
</div>
</body>
Creating ASP.NET Web API and consuming through html clients – 1
Now add the following script tag just after the </body> (closing body tag) to call web API
<script type="text/javascript">
var hostUrl = "http://" + document.location.hostname + ":" + window.location.port
;
var apiUrl = '/api/Product';
$(document).ready(function () { });
function GetAllProducts() {
$.ajax({
url: hostUrl + apiUrl,
type: 'GET',
dataType: 'json',
success: function (data) {
DisplayProductList(data);
},
error: function () {
alert('Some error occured');
}
});
}
function FindProduct() {
var id = $('#searchProductID').val();
$.getJSON(apiUrl + '/' + id)
.done(function (data) {
DisplayProductForEdit(data);
})
.fail(function (jqXHR, textStatus, err) {
$('#prod').text('Error: ' + err);
});
}
function DeleteProduct() {
var id = $('#delProductID').val();
$.ajax({
url: hostUrl + apiUrl + '/' + id,
type: 'DELETE',
dataType: 'json',
success: function (data) {
alert('Product deleted');
GetAllProducts();
},
error: function () {
alert('Product not found');
}
});
}
function UpdateProduct() {
var product = {
Id: $('#searchProductID').val(),
Name: $('#EditName').val(),
Type: $('#EditType').val(),
Description: $('#EditDescription').val(),
Price: $('#EditPrice').val()
};
$.ajax({
url: hostUrl + apiUrl,
type: 'PUT',
data: JSON.stringify(product),
contentType: "application/json;charset=utf-8",
success: function (data) {
alert('Employee updated');
GetAllEmployee();
},
error: function () {
alert('Some error occured');
}
});
}
function AddProduct() {
var product = {
Name: $('#Name').val(),
Type: $('#Type').val(),
Description: $('#Description').val(),
Price: $('#Price').val()
};
$.ajax({
url: hostUrl + apiUrl,
type: 'POST',
data: JSON.stringify(product),
contentType: "application/json;charset=utf-8",
success: function (data) {
alert('Product added');
GetAllProducts();
},
error: function () {
alert('Some error occured');
}
});
}
function DisplayProductList(products) {
$("#ProductList").empty();
var result = "<table><th>ID</th><th>Name</th><th>Type</th><th>Description</th
><th>Price</th>";
$.each(products, function (index, product) {
result += "<tr><td>" + product.Id + "</td><td> " + product.Name + "</td><
td>"
+ product.Type + "</td><td>" + product.Description + "</td><td>"
+ '₹ ' + product.Price + "</td></tr>";
});
result += "</table>";
$("#ProductList").html(result);
}
function DisplayProductForEdit(product) {
$("#prod").empty();
if (product == null) {
alert('Product Not Found')
return;
}
$("#prod").empty();
var result = "<table>" +
"<tr><td>Name</td><td><input type='text' id='EditName' value='" + product.Nam
e + "'</td></tr>" +
"<tr><td>Type</td><td><input type='text' id='EditType' value='" + product.Typ
e + "'</td></tr>" +
"<tr><td>Description</td><td><input type='text' id='EditDescription' value='
" + product.Description + "'</td></tr>" +
"<tr><td>Price</td><td><input type='text' id='EditPrice' value='" + product.P
rice + "'</td></tr>" +
"<tr><td colspan='3'align='center'><input type='button' value='Update' onclic
k='UpdateProduct();' </td></tr>" +
"</table>";
$("#prod").html(result);
}
</script>
Below are the screenshots for viewing all the products or finding a specific product.
Similarly, you can delete a product from the list by specifying its ID or add a new product.
Creating ASP.NET Web API and consuming through html clients – 2
Creating ASP.NET Web API and consuming through html clients – 3
Hurrah! now you have knowledge of creating ASP.NET Web API and consuming it through HTML
Clients. Don’t keep it to yourself. Please feel free to share your knowledge among your friends or
colleagues.

Weitere ähnliche Inhalte

Was ist angesagt?

Angular js filters and directives
Angular js filters and directivesAngular js filters and directives
Angular js filters and directivesDarryl Sherman
 
E by karan chanana
E by karan chananaE by karan chanana
E by karan chananakarnchanana
 
Training in Asp.net mvc3 platform-apextgi,noidaAspnetmvc3 j query
Training in Asp.net mvc3 platform-apextgi,noidaAspnetmvc3 j queryTraining in Asp.net mvc3 platform-apextgi,noidaAspnetmvc3 j query
Training in Asp.net mvc3 platform-apextgi,noidaAspnetmvc3 j queryprav068
 
Devoxx 2014-webComponents
Devoxx 2014-webComponentsDevoxx 2014-webComponents
Devoxx 2014-webComponentsCyril Balit
 
Training in Asp.net mvc3 platform-apextgi,noida
Training in Asp.net mvc3 platform-apextgi,noidaTraining in Asp.net mvc3 platform-apextgi,noida
Training in Asp.net mvc3 platform-apextgi,noidaprav068
 
Acceptance Testing with Webrat
Acceptance Testing with WebratAcceptance Testing with Webrat
Acceptance Testing with WebratLuismi Cavallé
 
QCon 2015 - Thinking in components: A new paradigm for Web UI
QCon 2015 - Thinking in components: A new paradigm for Web UIQCon 2015 - Thinking in components: A new paradigm for Web UI
QCon 2015 - Thinking in components: A new paradigm for Web UIOliver Häger
 
Your Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages SuckYour Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages SuckAnthony Montalbano
 
Aspnet mvc tutorial_9_cs
Aspnet mvc tutorial_9_csAspnet mvc tutorial_9_cs
Aspnet mvc tutorial_9_csMurali G
 
The go-start webframework (GTUG Vienna 27.03.2012)
The go-start webframework (GTUG Vienna 27.03.2012)The go-start webframework (GTUG Vienna 27.03.2012)
The go-start webframework (GTUG Vienna 27.03.2012)ungerik
 
МИХАЙЛО БОДНАРЧУК «SuperCharged End to End Testing with CodeceptJS» QADay 2019
МИХАЙЛО БОДНАРЧУК «SuperCharged End to End Testing with CodeceptJS»  QADay 2019МИХАЙЛО БОДНАРЧУК «SuperCharged End to End Testing with CodeceptJS»  QADay 2019
МИХАЙЛО БОДНАРЧУК «SuperCharged End to End Testing with CodeceptJS» QADay 2019GoQA
 
Form demoinplaywithmysql
Form demoinplaywithmysqlForm demoinplaywithmysql
Form demoinplaywithmysqlKnoldus Inc.
 

Was ist angesagt? (20)

Angular js filters and directives
Angular js filters and directivesAngular js filters and directives
Angular js filters and directives
 
E by karan chanana
E by karan chananaE by karan chanana
E by karan chanana
 
Training in Asp.net mvc3 platform-apextgi,noidaAspnetmvc3 j query
Training in Asp.net mvc3 platform-apextgi,noidaAspnetmvc3 j queryTraining in Asp.net mvc3 platform-apextgi,noidaAspnetmvc3 j query
Training in Asp.net mvc3 platform-apextgi,noidaAspnetmvc3 j query
 
Devoxx 2014-webComponents
Devoxx 2014-webComponentsDevoxx 2014-webComponents
Devoxx 2014-webComponents
 
[ HackFest.pl 2012] Testing - what for and how
[ HackFest.pl 2012] Testing - what for and how[ HackFest.pl 2012] Testing - what for and how
[ HackFest.pl 2012] Testing - what for and how
 
Unit testing UIView
Unit testing UIViewUnit testing UIView
Unit testing UIView
 
Borrador del blog
Borrador del blogBorrador del blog
Borrador del blog
 
Database connectivity in PHP
Database connectivity in PHPDatabase connectivity in PHP
Database connectivity in PHP
 
Training in Asp.net mvc3 platform-apextgi,noida
Training in Asp.net mvc3 platform-apextgi,noidaTraining in Asp.net mvc3 platform-apextgi,noida
Training in Asp.net mvc3 platform-apextgi,noida
 
Acceptance Testing with Webrat
Acceptance Testing with WebratAcceptance Testing with Webrat
Acceptance Testing with Webrat
 
QCon 2015 - Thinking in components: A new paradigm for Web UI
QCon 2015 - Thinking in components: A new paradigm for Web UIQCon 2015 - Thinking in components: A new paradigm for Web UI
QCon 2015 - Thinking in components: A new paradigm for Web UI
 
Java Script
Java ScriptJava Script
Java Script
 
Your Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages SuckYour Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages Suck
 
13. view data
13. view data13. view data
13. view data
 
Aspnet mvc tutorial_9_cs
Aspnet mvc tutorial_9_csAspnet mvc tutorial_9_cs
Aspnet mvc tutorial_9_cs
 
Karan
KaranKaran
Karan
 
The go-start webframework (GTUG Vienna 27.03.2012)
The go-start webframework (GTUG Vienna 27.03.2012)The go-start webframework (GTUG Vienna 27.03.2012)
The go-start webframework (GTUG Vienna 27.03.2012)
 
МИХАЙЛО БОДНАРЧУК «SuperCharged End to End Testing with CodeceptJS» QADay 2019
МИХАЙЛО БОДНАРЧУК «SuperCharged End to End Testing with CodeceptJS»  QADay 2019МИХАЙЛО БОДНАРЧУК «SuperCharged End to End Testing with CodeceptJS»  QADay 2019
МИХАЙЛО БОДНАРЧУК «SuperCharged End to End Testing with CodeceptJS» QADay 2019
 
Form demoinplaywithmysql
Form demoinplaywithmysqlForm demoinplaywithmysql
Form demoinplaywithmysql
 
Shell
ShellShell
Shell
 

Andere mochten auch

20130930 衛環委員會 - 102年度中央政府總預算行政院衛生署暨所屬公務預算解凍案
20130930 衛環委員會 - 102年度中央政府總預算行政院衛生署暨所屬公務預算解凍案20130930 衛環委員會 - 102年度中央政府總預算行政院衛生署暨所屬公務預算解凍案
20130930 衛環委員會 - 102年度中央政府總預算行政院衛生署暨所屬公務預算解凍案R.O.C.Ministry of Health and Welfare
 
Valorar más que el precio
Valorar más que el precioValorar más que el precio
Valorar más que el precioCBRETasaciones
 
PDHPE presentation
PDHPE presentationPDHPE presentation
PDHPE presentationZeinabHabib
 
Untitled Presentation
Untitled PresentationUntitled Presentation
Untitled PresentationLizzy Parsons
 
OER: Benefits and Challenges
OER: Benefits and ChallengesOER: Benefits and Challenges
OER: Benefits and ChallengesPaul Eldridge
 
해외안전공원 해외안전공원추천 메이저공원추천 메이저공원
해외안전공원 해외안전공원추천 메이저공원추천 메이저공원해외안전공원 해외안전공원추천 메이저공원추천 메이저공원
해외안전공원 해외안전공원추천 메이저공원추천 메이저공원pildu gong
 
CV - mohammed khamis aburuka MBA
CV - mohammed khamis aburuka MBACV - mohammed khamis aburuka MBA
CV - mohammed khamis aburuka MBAMohammed A.Khamis
 

Andere mochten auch (13)

20130930 衛環委員會 - 102年度中央政府總預算行政院衛生署暨所屬公務預算解凍案
20130930 衛環委員會 - 102年度中央政府總預算行政院衛生署暨所屬公務預算解凍案20130930 衛環委員會 - 102年度中央政府總預算行政院衛生署暨所屬公務預算解凍案
20130930 衛環委員會 - 102年度中央政府總預算行政院衛生署暨所屬公務預算解凍案
 
Valorar más que el precio
Valorar más que el precioValorar más que el precio
Valorar más que el precio
 
PDHPE presentation
PDHPE presentationPDHPE presentation
PDHPE presentation
 
Dharik_Soni
Dharik_SoniDharik_Soni
Dharik_Soni
 
Untitled Presentation
Untitled PresentationUntitled Presentation
Untitled Presentation
 
OER: Benefits and Challenges
OER: Benefits and ChallengesOER: Benefits and Challenges
OER: Benefits and Challenges
 
The beautiful-game
The beautiful-gameThe beautiful-game
The beautiful-game
 
해외안전공원 해외안전공원추천 메이저공원추천 메이저공원
해외안전공원 해외안전공원추천 메이저공원추천 메이저공원해외안전공원 해외안전공원추천 메이저공원추천 메이저공원
해외안전공원 해외안전공원추천 메이저공원추천 메이저공원
 
CV - mohammed khamis aburuka MBA
CV - mohammed khamis aburuka MBACV - mohammed khamis aburuka MBA
CV - mohammed khamis aburuka MBA
 
ESO3 Mecanismes
ESO3 MecanismesESO3 Mecanismes
ESO3 Mecanismes
 
Gomc 2012 learning plan
Gomc 2012 learning planGomc 2012 learning plan
Gomc 2012 learning plan
 
SANLEC
SANLECSANLEC
SANLEC
 
CV_Dr.Erssido March 2016
CV_Dr.Erssido March 2016CV_Dr.Erssido March 2016
CV_Dr.Erssido March 2016
 

Ähnlich wie Creating web api and consuming part 2

HTML5 New and Improved
HTML5   New and ImprovedHTML5   New and Improved
HTML5 New and ImprovedTimothy Fisher
 
GDI Seattle - Intro to JavaScript Class 4
GDI Seattle - Intro to JavaScript Class 4GDI Seattle - Intro to JavaScript Class 4
GDI Seattle - Intro to JavaScript Class 4Heather Rock
 
Enjoy the vue.js
Enjoy the vue.jsEnjoy the vue.js
Enjoy the vue.jsTechExeter
 
Vaadin Components @ Angular U
Vaadin Components @ Angular UVaadin Components @ Angular U
Vaadin Components @ Angular UJoonas Lehtinen
 
Ôn tập KTTMDT
Ôn tập KTTMDTÔn tập KTTMDT
Ôn tập KTTMDTmrcoffee282
 
HTML5 and the dawn of rich mobile web applications pt 2
HTML5 and the dawn of rich mobile web applications pt 2HTML5 and the dawn of rich mobile web applications pt 2
HTML5 and the dawn of rich mobile web applications pt 2James Pearce
 
jQuery Mobile - Desenvolvimento para dispositivos móveis
jQuery Mobile - Desenvolvimento para dispositivos móveisjQuery Mobile - Desenvolvimento para dispositivos móveis
jQuery Mobile - Desenvolvimento para dispositivos móveisPablo Garrido
 
MVC and Razor - Doc. v1.2
MVC and Razor - Doc. v1.2MVC and Razor - Doc. v1.2
MVC and Razor - Doc. v1.2Naji El Kotob
 
Design Patterns for JavaScript Web Apps - JavaScript Conference 2012 - OPITZ ...
Design Patterns for JavaScript Web Apps - JavaScript Conference 2012 - OPITZ ...Design Patterns for JavaScript Web Apps - JavaScript Conference 2012 - OPITZ ...
Design Patterns for JavaScript Web Apps - JavaScript Conference 2012 - OPITZ ...OPITZ CONSULTING Deutschland
 
Jquery presentation
Jquery presentationJquery presentation
Jquery presentationguest5d87aa6
 
Pengenalan AngularJS
Pengenalan AngularJSPengenalan AngularJS
Pengenalan AngularJSEdi Santoso
 

Ähnlich wie Creating web api and consuming part 2 (20)

Practica n° 7
Practica n° 7Practica n° 7
Practica n° 7
 
Lab final
Lab finalLab final
Lab final
 
HTML5 New and Improved
HTML5   New and ImprovedHTML5   New and Improved
HTML5 New and Improved
 
GDI Seattle - Intro to JavaScript Class 4
GDI Seattle - Intro to JavaScript Class 4GDI Seattle - Intro to JavaScript Class 4
GDI Seattle - Intro to JavaScript Class 4
 
Enjoy the vue.js
Enjoy the vue.jsEnjoy the vue.js
Enjoy the vue.js
 
Vaadin Components @ Angular U
Vaadin Components @ Angular UVaadin Components @ Angular U
Vaadin Components @ Angular U
 
Ôn tập KTTMDT
Ôn tập KTTMDTÔn tập KTTMDT
Ôn tập KTTMDT
 
JavaScript Training
JavaScript TrainingJavaScript Training
JavaScript Training
 
HTML5 and the dawn of rich mobile web applications pt 2
HTML5 and the dawn of rich mobile web applications pt 2HTML5 and the dawn of rich mobile web applications pt 2
HTML5 and the dawn of rich mobile web applications pt 2
 
course js day 3
course js day 3course js day 3
course js day 3
 
lect4
lect4lect4
lect4
 
lect4
lect4lect4
lect4
 
jQuery Mobile - Desenvolvimento para dispositivos móveis
jQuery Mobile - Desenvolvimento para dispositivos móveisjQuery Mobile - Desenvolvimento para dispositivos móveis
jQuery Mobile - Desenvolvimento para dispositivos móveis
 
MVC and Razor - Doc. v1.2
MVC and Razor - Doc. v1.2MVC and Razor - Doc. v1.2
MVC and Razor - Doc. v1.2
 
Java script cookies
Java script   cookiesJava script   cookies
Java script cookies
 
Design Patterns for JavaScript Web Apps - JavaScript Conference 2012 - OPITZ ...
Design Patterns for JavaScript Web Apps - JavaScript Conference 2012 - OPITZ ...Design Patterns for JavaScript Web Apps - JavaScript Conference 2012 - OPITZ ...
Design Patterns for JavaScript Web Apps - JavaScript Conference 2012 - OPITZ ...
 
Backbone - TDC 2011 Floripa
Backbone - TDC 2011 FloripaBackbone - TDC 2011 Floripa
Backbone - TDC 2011 Floripa
 
Lecture-5.pptx
Lecture-5.pptxLecture-5.pptx
Lecture-5.pptx
 
Jquery presentation
Jquery presentationJquery presentation
Jquery presentation
 
Pengenalan AngularJS
Pengenalan AngularJSPengenalan AngularJS
Pengenalan AngularJS
 

Kürzlich hochgeladen

AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfryanfarris8
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 

Kürzlich hochgeladen (20)

AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 

Creating web api and consuming part 2

  • 1. Creating Asp.net Web API and consuming it through HTML Clients – Part II Howdy Readers, Consuming web API through HTML clients Welcome to our blog ! In our previous post we have seen how to create ASP.NET Web API. If you aren’t still comfortable in creating Web API then I would suggest you to read our post for creating Web API. Today, we will be focusing on consuming web API through HTML clients. Trust me guys, it’s very easy to consume web API and we will do that using JQuery. If you are unfamiliar with JQuery then please refer w3 schools for getting some basic idea about it. Latest version of Jquery can be downloaded from here. Modify the default file “index.cshtml” in the View/Home folder with the following Markup to provide a GUI for Displaying Products and their different actions. <!DOCTYPE html> <html lang="en"> <body> <header> <script type="text/javascript" src="../../Scripts/jquery-1.8.2.js"></script> </header> <div id="body"> <section class="featured"> <div class="content-wrapper"> <hgroup class="title"> <h1>Welcome to ASP.NET Web API | Demo by <a href="http://dipendra shekhawat.com" target="_blank">Dipendra Shekhawat</a></h1>
  • 2. </hgroup> </div> </section> <section class="content-wrapper main-content clear-fix"> <div> <h4>Product List</h4> <input type="button" value="View All Products" onclick="GetAllProduct s();" /> <ul id="ProductList" /> </div> <div> <h4>Search by ID</h4> <input type="text" id="searchProductID" size="5" /> <input type="button" value="Search" onclick="FindProduct();" /> <p id="prod" /> </div> <div> <h4>Delete Product by ID</h4> <input type="text" id="delProductID" size="5" /> <input type="button" value="Delete" onclick="DeleteProduct();" /> </div> <div> <h4>Add Product </h4> <table> <tr> <td>Name</td> <td><input type="text" id="Name" /></td> </tr> <tr>
  • 3. <td>Type</td> <td><input type="text" id="Type" /></td> </tr> <tr> <td>Description</td> <td><input type="text" id="Description" /></td> </tr> <tr> <td>Price</td> <td><input type="text" id="Price" /></td> </tr> <tr> <td colspan="3" align="center"> <input type="button" value="Add" onclick="AddProduct(); " /></td> </tr> </table> </div> </section> </div> </body>
  • 4. Creating ASP.NET Web API and consuming through html clients – 1 Now add the following script tag just after the </body> (closing body tag) to call web API <script type="text/javascript"> var hostUrl = "http://" + document.location.hostname + ":" + window.location.port ; var apiUrl = '/api/Product'; $(document).ready(function () { }); function GetAllProducts() { $.ajax({ url: hostUrl + apiUrl, type: 'GET',
  • 5. dataType: 'json', success: function (data) { DisplayProductList(data); }, error: function () { alert('Some error occured'); } }); } function FindProduct() { var id = $('#searchProductID').val(); $.getJSON(apiUrl + '/' + id) .done(function (data) { DisplayProductForEdit(data); }) .fail(function (jqXHR, textStatus, err) { $('#prod').text('Error: ' + err); }); } function DeleteProduct() { var id = $('#delProductID').val(); $.ajax({ url: hostUrl + apiUrl + '/' + id, type: 'DELETE', dataType: 'json', success: function (data) {
  • 6. alert('Product deleted'); GetAllProducts(); }, error: function () { alert('Product not found'); } }); } function UpdateProduct() { var product = { Id: $('#searchProductID').val(), Name: $('#EditName').val(), Type: $('#EditType').val(), Description: $('#EditDescription').val(), Price: $('#EditPrice').val() }; $.ajax({ url: hostUrl + apiUrl, type: 'PUT', data: JSON.stringify(product), contentType: "application/json;charset=utf-8", success: function (data) { alert('Employee updated'); GetAllEmployee(); }, error: function () { alert('Some error occured');
  • 7. } }); } function AddProduct() { var product = { Name: $('#Name').val(), Type: $('#Type').val(), Description: $('#Description').val(), Price: $('#Price').val() }; $.ajax({ url: hostUrl + apiUrl, type: 'POST', data: JSON.stringify(product), contentType: "application/json;charset=utf-8", success: function (data) { alert('Product added'); GetAllProducts(); }, error: function () { alert('Some error occured'); } }); } function DisplayProductList(products) { $("#ProductList").empty();
  • 8. var result = "<table><th>ID</th><th>Name</th><th>Type</th><th>Description</th ><th>Price</th>"; $.each(products, function (index, product) { result += "<tr><td>" + product.Id + "</td><td> " + product.Name + "</td>< td>" + product.Type + "</td><td>" + product.Description + "</td><td>" + '₹ ' + product.Price + "</td></tr>"; }); result += "</table>"; $("#ProductList").html(result); } function DisplayProductForEdit(product) { $("#prod").empty(); if (product == null) { alert('Product Not Found') return; } $("#prod").empty(); var result = "<table>" + "<tr><td>Name</td><td><input type='text' id='EditName' value='" + product.Nam e + "'</td></tr>" + "<tr><td>Type</td><td><input type='text' id='EditType' value='" + product.Typ e + "'</td></tr>" + "<tr><td>Description</td><td><input type='text' id='EditDescription' value=' " + product.Description + "'</td></tr>" + "<tr><td>Price</td><td><input type='text' id='EditPrice' value='" + product.P rice + "'</td></tr>" + "<tr><td colspan='3'align='center'><input type='button' value='Update' onclic k='UpdateProduct();' </td></tr>" +
  • 9. "</table>"; $("#prod").html(result); } </script> Below are the screenshots for viewing all the products or finding a specific product. Similarly, you can delete a product from the list by specifying its ID or add a new product. Creating ASP.NET Web API and consuming through html clients – 2
  • 10. Creating ASP.NET Web API and consuming through html clients – 3 Hurrah! now you have knowledge of creating ASP.NET Web API and consuming it through HTML Clients. Don’t keep it to yourself. Please feel free to share your knowledge among your friends or colleagues.