This article explains how to create a simple application using knockout.js with the ASP.NET Web API. In this article, we create a database, and we can update and delete the data of the database with this application. Knockout js is the JavaScript implementation for creating the rich, responsive display and editor user interfaces with a clean underlying data model. It is an open-source library implemented entirely in JavaScript.
Binding:
- data-bind: It is used as HTML attributes.
- Ko.oberserable: It is a property that wraps the object property with a custom function.
Use the following procedure to create a sample application.
Step 1
First, we create a database with the table "CustomerInfo".
- use mudita
- Create table CustomerInfo(CustNo int IDENTITY(1,1) PRIMARY KEY NOT NULL, CustName varchar(10) NOT NULL,Salary decimal(18,0)NOT NULL, DeptName varchar(50) Not Null)
Step 2
Create a Web API application as in the following:
- Start Visual Studio 2012.
- From the Start window select "Installed" -> "Visual C#" -> "Web".
- Select "ASP .NET MVC4 Web Application' and click on the "OK" button.
- From the "MVC4 Project" window select "Web API".
- Click on the "OK" button.
Step 3
Now add the ADO.NET Entity Data Model to the project.
- In the Solution Explorer.
- Right-click on the Model folder then select "Add" -> "New Item".
- From the template window select "Installed" -> "Data" and then select "ADO.NET Data Model".
Open a window select Generate from the database.
Click on the "Next" button and open a dialog box then click on "New Connection".
Select the server name and database and click on the "Ok" button.
Now from the entity data model wizard select the table and click on the "Finish" button.
Step 4
Add an API Controller:
- In the "Solution Explorer".
- Right-click on the Controller folder and select "Add" -> "Controller".
- Select an API controller with read /write actions using Entity Framework.
- Select Model class and Data Context.
- Click on the "Add" button.
Step 5
Now we create an MVC Controller"CustomerInfoController.cs" and add a Create Action method "Create". And create a View of the "Create" action method.
Add the following code in the View:
- @{
- ViewBag.Title = "Create";
- }
- <h2>Create</h2>
- <html>
- <h2>Create</h2>
- <head>
- <script src="~/Scripts/jquery-1.8.2.js"></script>
- <script src="~/Scripts/knockout-2.2.0.js"></script>
- <script src="~/Scripts/knockout.mapping-latest.js"></script>
- <link href="~/Content/Site.css" rel="stylesheet" />
- </head>
- <body>
- <form>
- <table>
- <tr>
- <td>
- <!--Bind the TextBoxes in the Table to the observable properties defined into the ViewModel -->
- <table id="tbldml">
- <tr>
- <td>CustNo</td>
- <td>
- <input type="text" id="txteno" data-bind="value: $root.CustNo" disabled="disabled" /></td>
- </tr>
- <tr>
- <td>CustName</td>
- <td>
- <input type="text" id="txtename" data-bind="value: $root.CustName" /></td>
- </tr>
- <tr>
- <td>Salary</td>
- <td>
- <input type="text" id="txtsal" data-bind="value: $root.Salary" /></td>
- </tr>
- <tr>
- <td>DeptName</td>
- <td>
- <input type="text" id="txtdname" data-bind="value: $root.DeptName" /></td>
- </tr>
- <tr>
- <!--The click binding has the JavaScirpt methods passed to it-->
- <td>
- <button data-bind="click :$root.save">Save</button></td>
- <td>
- <button data-bind="click: $root.update">Update</button></td>
- </tr>
- </table>
- </td>
- <td>
- <div class="FixedContainer">
- <table data-bind="visible: Customers().length>0" style="border: double">
- <thead>
- <tr>
- <td>CustNo</td>
- <td>CustName</td>
- <td>Salary</td>
- <td>DeptName</td>
- <td></td>
- </tr>
- </thead>
- <!--Iterate through an observableArray using foreach-->
- <tbody data-bind="foreach: Customers">
- <tr style="border: solid" data-bind="click: $root.getselectedcustomer" id="updtr">
- <td><span data-bind="text: CustNo"></span></td>
- <td><span data-bind="text: CustName"></span></td>
- <td><span data-bind="text: Salary"></span></td>
- <td><span data-bind="text: DeptName"></span></td>
- <td>
- <button data-bind="click: $root.deleterec">Delete</button></td>
- </tr>
- </tbody>
- </table>
- </div>
- </td>
- </tr>
- </table>
- </form>
- <script type="text/javascript">
- var CustViewModel = function() {
- //Make the self as 'this' reference
- var self = this;
- //Declare observable which will be bind with UI
- self.CustNo = ko.observable("0");
- self.CustName = ko.observable("");
- self.Salary = ko.observable("");
- self.DeptName = ko.observable("");
- //The Object which stored data entered in the observables
- var CustData = {
- CustNo: self.CustNo,
- CustName: self.CustName,
- Salary: self.Salary,
- DeptName: self.DeptName,
- };
- //Declare an ObservableArray for Storing the JSON Response
- self.Customers = ko.observableArray([]);
- GetCustomers(); //Call the Function which gets all records using ajax call
- self.save = function() {
- //Ajax call to Insert the Customer record
- $.ajax({
- type: "POST",
- url: "http://localhost:55333//api/CustomerInfoAPI",
- data: ko.toJSON(CustData), //Convert the Observable Data into JSON
- contentType: "application/json",
- success: function(data) {
- alert("Record Added Successfully");
- self.CustNo(data.CustNo);
- alert("The New Customer Id :" + self.CustNo());
- GetCustomers();
- },
- error: function() {
- alert("Failed");
- }
- });
- //Ends Here
- };
- self.update = function() {
- var url = "http://localhost:55333//api/CustomerInfoAPI/" + self.CustNo();
- alert(url);
- $.ajax({
- type: "PUT",
- url: url,
- data: ko.toJSON(CustData),
- contentType: "application/json",
- success: function(data) {
- alert("Record Updated Successfully");
- GetCustomers();
- },
- error: function(error) {
- alert(error.status + "<!----!>" + error.statusText);
- }
- });
- };
- //Function to perform DELETE Operation
- self.deleterec = function(customer) {
- $.ajax({
- type: "DELETE",
- url: "http://localhost:55333//api/CustomerInfoAPI/" + customer.CustNo,
- success: function(data) {
- alert("Record Deleted Successfully");
- GetCustomers(); //Refresh the Table
- },
- error: function(error) {
- alert(error.status + "<--and--> " + error.statusText);
- }
- });
- };
- function GetCustomers() {
- $.ajax({
- type: "GET",
- url: "http://localhost:55333//api/CustomerInfoAPI",
- contentType: "application/json; charset=utf-8",
- dataType: "json",
- success: function(data) {
- self.Customers(data); //Put the response in ObservableArray
- },
- error: function(error) {
- alert(error.status + "<--and--> " + error.statusText);
- }
- });
- //Ends Here
- }
- //Function to Display record to be updated
- self.getselectedcustomer = function(customer) {
- self.CustNo(customer.CustNo),
- self.CustName(customer.CustName),
- self.Salary(customer.Salary),
- self.DeptName(customer.DeptName)
- };
- };
- ko.applyBindings(new CustViewModel());
- </script>
- </body>
- </html>
Step 6
Execute the application. Fill in a record and click on the "Save" button. It then displays a successful submission message.
Update the record. Change a record and click on the "Update" button. Here we update "Tanya" with "Priya". It updates the record.
For deleting the record click on the "Delete" button. You can see that it deletes the record.
Record deleted
We can also see our database using the command:
- Select * from CustomerInfo
No comments:
Post a Comment