Microsoft has provided the developer community with a brand new execution environment and a collection of new APIs called WinRT to develop UI rich full screen applications known as Metro-Style Applications. These applications can be developed on Windows 8 using VS 2012 (currently not released and available as a Release Candidate) and can be used on Windows 8 Tables devices. The nicest part of these applications is they can be developed using XAML and C#, HTML5 and JavaScript (or jQuery). Since HTML5 based is used for developing UI and jQuery can be used to make external calls to WCF services and Web API, we can easily develop business applications for those users who are just interested in using applications for business use than an application developed using a specific technology.
In the application, we will talk about establishing communications between ASP.NET WEB API and Metro-Style application using jQuery for performing CRUD operations. The ASP.NET WEB API is a new framework provided in .NET 4.5 using which operations can be directly exposed to HTTP and clients created using JavaScript, jQuery can make calls to these operations using GET, POST, PUT and DELETE methods. Advantages of such an approach is that the end-user is free to make use of any device e.g. Tables, mobile device etc to use his/her business applications.
For this application I am using SQL Server as a data store with the following table:
Step 1: Open VS 2012 and create a blank solution, name it as ‘Metro_JS_Web_API’. In this solution, add a new ASP.NET Web Application, name it as ‘Web_App_WebAPI’.
Step 2: In this web application, add a new WEB API Controller class as shown below:
Step 3: In the Web Application project, add a new class file and name it as DataClasses.cs and add the following classes in it. These classes will perform operations for making a call to the database table and perform CRUD operations. I am just listing some skeleton code here. You can view the internal workings of this code in the source code of this article
namespace WebApp_Web_API
{
public class EmployeeInfo
{
public int EmpNo { get; set; }
public string EmpName { get; set; }
public int Salary { get; set; }
public string DeptName { get; set; }
public string Designation { get; set; }
}
public class EmployeeInfoDAL
{
SqlConnection Conn;
SqlDataAdapter AdEmp;
DataSet Ds;
public EmployeeInfoDAL()
{
}
public List<EmployeeInfo> GetEmployees()
{
}
public void CreateEmployee(EmployeeInfo objEmp)
{
}
public void UpdateEmployee(EmployeeInfo objEmp)
{
}
public void DeleteEmployee(int EmpNo)
{
}
}
}
Step 4: Change the implementation of the EmployeeController class as shown below:
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace WebApp_Web_API
{
public class EmployeeController : ApiController
{
EmployeeInfoDAL objContext;
public EmployeeController()
{
objContext = new EmployeeInfoDAL();
}
// GET /api/<controller>
public IEnumerable<EmployeeInfo> Get()
{
return objContext.GetEmployees().ToList();
}
// GET /api/<controller>/5
public EmployeeInfo Get(int id)
{
var Emp = objContext.GetEmployees()
.ToList().Find(e => e.EmpNo == id);
return Emp;
}
// POST /api/<controller>
public void Post(EmployeeInfo Emp)
{
objContext.CreateEmployee(Emp);
}
// PUT /api/<controller>/5
[HttpPut]
public void Put(int id,EmployeeInfo objEmp)
{
var Emp = objContext.GetEmployees()
.ToList().Find(e => e.EmpNo == objEmp.EmpNo);
Emp = objEmp;
objContext.UpdateEmployee(Emp);
}
// DELETE /api/<controller>/5
public void Delete(int id)
{
objContext.DeleteEmployee(id);
}
}
}
If you carefully look at the class, you will find that the WEB API controller class provides method compatible to HTTP methods, as shown below:
These methods perform data communication using JavaScript Object Notation (JSON). Hence we can directly expose these methods to a client created in say jQuery.
Step 5: Now we will register the routing map for the above methods in our Global.asax file so that the client can make call to these methods using HTTP based URL. Open Global.asax file and add the following Route map in the Application_Start event:
RouteTable.Routes.MapHttpRoute(name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = System.Web.Http.RouteParameter.Optional });
Step 6: To support HTTP PUT and DELETE methods of communication and processing on the server side, add the following configuration in the config file of the Web Application:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
Build the application and make sure that it is error free.
Consuming the WEB API in a Metro-Style JavaScript Application
Step 1: To the above solution, add a new Metro-Style application from the JavaScript template as shown below:
Name the application as ‘Metro_JS_Web_API’.
Step 2: Here I am using jQuery to make a call to the WEB API. I am using jQuery 1.6.2 kept in the .js folder, kept in the Scripts folder of the Web Application. (Note: You can add the latest version – 1.7.3)
Step 3: Open default.html and add the following Html :
<body>
<h1>Employees App</h1>
<table style="width: 100%;">
<tr>
<td>EmpNo
</td>
<td>
<input type="text" id="txteno" />
</td>
<td>
<input type="button" value="Get Details" id="btnGetDetails" />
</td>
</tr>
<tr>
...
...
</tr>
</table>
</body>
Note: It’s a good idea to use a templating engine like jsTemplate here. We will keep that for another article.
Step 4: Display All Employees
Write the following JavaScript which makes an AJAX call to the WEB API and reads some JSON data.
$(document).ready(function () {
$.ajax({
type: "GET",
url: "http://localhost:1045/api/Employee",
datatype: "json",
success: function (data) {
$.each(data,function (idx,ele) {
$('#grdData').append('<tr><td>' + ele.EmpNo +
'</td><td>' + ele.EmpName + '</td><td>' + ele.Salary +
'</td><td>'+ele.DeptName+'</td><td>'+ele.Designation+'</td></tr>');
});
}
});
});
The above code makes an ansyc call to ASP.NET WEB API using $.ajax method. A successful execution will return JSON which will be displayed in the HTML Table. Run the application and the result will be as shown below:
Step 5: Reading a Specific Record
Add the following helper method to clear all TextBoxes:
function clearAll()
{
$("#txteno").val("");
$("#txtename").val("");
$("#txtsal").val("");
$("#txtdname").val("");
$("#txtdesig").val("");
}
If you have a common class assigned to these textboxes, you can even use the following:
$('.commonClassName input').val('');
or if these textboxes are clubbed into a div, just use
$('#divID input').val('');
Now add the following script in the Click event of the ‘Get Details’ HTML button. This will make use of jQuery $.getJSON method to retrieve a specific record from the Data Table using WEB API:
$("#btnGetDetails").click(function () {
var data = $("#txteno").val();
var url = "http://localhost:1045/api/Employee/" + data;
$.getJSON(url, function (EmpRec) {
$("#txtename").val(EmpRec.EmpName);
$("#txtsal").val(EmpRec.Salary);
$("#txtdname").val(EmpRec.DeptName);
$("#txtdesig").val(EmpRec.Designation);
});
});
Run the application and enter a number in the EmpNo textbox and click on ‘Get Details’ button the result will be as below:
Step 6: Adding a new Record.
On the click event of the ‘New’ button, call the ‘ClearAll’ method to clear all TextBoxes:
$("#btnNew").click(function () {
clearAll();
});
You can even write this code as:
$('#btnNew').bind('click', function() {
$('#divID input').val('');
});
where the above code assumes that all your input boxes are inside a div called ‘divID’
With the Metro Applications using JavaScript, we have been provided with ‘WinJS’ object. This is used to make GET and POST operations. This object is provided in the JavaScript file already referred in the default.html as below
<script src="//Microsoft.WinJS.1.0.RC/js/base.js"></script>
Write the following script in the Click event of the ‘Add’ button:
$("#btnAdd").click(function () {
//Declare Object
var Emp = {};
Emp.EmpName = $("#txtename").val();
Emp.Salary = $("#txtsal").val();
Emp.DeptName = $("#txtdname").val();
Emp.Designation = $("#txtdesig").val();
//Get Url
var createurl = "http://localhost:1045/api/Employee/";
//POST data
WinJS.xhr({
type: "POST",
url: createurl,
headers: { "Content-type": "application/json; charset=utf-8" },
data: JSON.stringify(Emp)
}).then(success, error);
});
function success() {
$("#txtmsg").val("Inserted...");
}
function error() {
$("#txtmsg").val("Failed...");
}
$("#btnAdd").click(function () {
//Declare Object
var Emp = {};
Emp.EmpName = $("#txtename").val();
Emp.Salary = $("#txtsal").val();
Emp.DeptName = $("#txtdname").val();
Emp.Designation = $("#txtdesig").val();
//Get Url
var createurl = "http://localhost:1045/api/Employee/";
//POST data
WinJS.xhr({
type: "POST",
url: createurl,
headers: { "Content-type": "application/json; charset=utf-8" },
data: JSON.stringify(Emp)
}).then(success, error);
});
function success() {
$("#txtmsg").val("Inserted...");
}
function error() {
$("#txtmsg").val("Failed...");
}
The WinJX.xhr() accepts the following parameters:
- type: specify the HTTP method to perform.
- url: The http based repository to which call is made and data is send.
- headers: Specifies the type of data passed.
- data: Data sent with request.
‘then’ is used to capture the success/failure notification returned from the request.
Run the application and enter data in TextBoxes (EmpNo is identity) and click on the ‘Add’ button. If the save is successful, then the ‘Inserted…’ message will be displayed in the status TextBox
Step 7: Implement Update and Delete
Write the following Script in the click event of the ‘Update’ and ‘Delete’ buttons:
$("#btnUpdate").click(function () {
//Declare Object
var Emp = {};
//Assign Values
Emp["EmpNo"] = $("#txteno").val();
Emp["EmpName"] = $("#txtename").val();
Emp["Salary"] = $("#txtsal").val();
Emp["DeptName"] = $("#txtdname").val();
Emp["Designation"] = $("#txtdesig").val();
//Get Url
var url1 = "http://localhost:1045/api/Employee/" + Emp["EmpNo"];
//Make an Ajax Call for PUT operations
$.ajax({
type: "PUT",
url: url1,
contentType: "application/json; charset=utf-8",
data:JSON.stringify(Emp),
statusCode: {
200: function () { $("#txtmsg").val("done"); }
},
error:
function (res) { $("#txtmsg").val("error" + " "
+ res.status + " " + res.statusText); }
});
});
$("#btnDelete").click(function(){
var EmpNo = $("#txteno").val();
$.ajax({
type: 'DELETE',
url: "http://localhost:1045/api/Employee/" + EmpNo,
statusCode: {
200: function () { $("#txtmsg").val("done"); }
},
error:
function (res) { $("#txtmsg").val("error" + " "
+ res.status + " " + res.statusText); }
});
clearAll();
});
Test the above functionality by clicking on the Update and Delete buttons.
Conclusion:
Microsoft is committed to contributing to the future of technology in a big way and WinRT and metro-style apps are just the start. HTML 5 and JavaScript with WEB API integration helps developer to develop decoupled application. It’s exciting times ahead!
The entire source code of the article can be downloaded over here
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!
Was this article worth reading? Share it with fellow developers too. Thanks!
Mahesh Sabnis is a DotNetCurry author and a Microsoft MVP having over two decades of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions), and Front-end technologies like Angular and React. Follow him on twitter @
maheshdotnet or connect with him on
LinkedIn