Skip to main content

Simple data binding with Knockout, Web API and ASP.Net Web Forms

In this post We are going to see How Knockout, ASP.Net Web API and ASP.Net works together smoothly. There are lots many examples of ASP.Net MVC,Web API and Knockout.js available on web working together  nicely. So I thought it will be a good idea to write a blog post about how ASP.Net Web API, ASP.Net Web Forms,Knockout.js works together and how we can create simple data binding with Knockout.js.

ASP.Net Web Forms:


As we all know ASP.Net Web Forms is one of premier development technology widely use in creating web sites and web applications. ASP.Net Web Forms allow to create dynamic websites using event driven model. It is one of the easiest way to create web applications and web sites.


ASP.Net Web API:


ASP.Net Web API is a framework that allows to build HTTP Service that reach a broad range of clients including browsers and mobile devices.It provides very easy way to write restful http services. Its can be access by any type of client over HTTP protocol. Client can make a GET, PUT,POST and DELETE request based on its requirement and get the response appropriately.

Knockout JS:


As per knockoutjs.com, Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model. It provides a way to declarative bindings using an ‘Observable’ view model on browser. It supports two way bindings.

Getting Started with ASP.Net Web Forms and ASP.Net Web API:


So let’s get started  first we have to create an empty web forms application in Visual Studio 2012 via File->New Project Menu.

Creating asp.net web forms application for knockout demo

Now once application created we need to add reference to System.Web.Routing as we need to required routing for the ASP.Net Web API.

AddReferenceSystemwebrouting

Now It’s time to create a model class that we are going to use for Web API. Following a code for that class. It’s very basic as we are just creating sample demo. So I have created class with 3 properties.

namespace WebApplication1.App_Code
{
    public class Employee
    {
        public int  EmployeeId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}

Now let’s add Web Api Controller Class to create a basic Web API.

Creating a Web API class in asp.net web forms

Now it’s time to write a code for the our ASP.Net Web API Employee Controller and following code I have written for that. here I have created a list of employee and written that in GetEmployeee method.

using System;
using System.Collections.Generic;
using System.Web.Http;

namespace WebApplication1.App_Code
{
    public class EmployeeController : ApiController
    {
        public List<Employee> Employees = new List<Employee> { 
            new Employee {EmployeeId=1,FirstName="Jalpesh",LastName="Vadgama"},
            new Employee {EmployeeId=2,FirstName="Vishal",LastName="Vadgama"},
            new Employee {EmployeeId=3,FirstName="Tushar",LastName="Maru"},
            new Employee {EmployeeId=4,FirstName="Himanshu",LastName="Patel"},
        };

        public IEnumerable<Employee> GetEmployees()
        {
            return Employees;
        }
    }
}

As now our Web API ready and we need to add a route for our API to handle a request. So let’s first add Global Application Class.

GlobalApplicationClass

Now in application_start I have written following code to create a route for web api.

protected void Application_Start(object sender, EventArgs e)
{
    RouteTable.Routes.MapHttpRoute(
             name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
             defaults: new { id = System.Web.Http.RouteParameter.Optional }
             );

}

Here I have just define route as api/controller so our URL will like this. http://localhost/api/employee

So now our API is almost ready. So It’s time to add scripts that we are going to use via NuGet package. We need to two script files jQuery for initial handling and making ajax calls and knockoutjs for bindings.

JqueryNuget

same way for knockout.

KnockOutNuGetPackage

So we are ready to write a code calling API from JavaScript and perform binding for the knockout. So let’s first create a empty web form page and then we write some code in that.

Adding a web form to write code for knockout

Now first I have included both scripts in default.aspx head tag like following.

<head runat="server">
    <script src="Scripts/jquery-2.0.0.min.js"></script>
    <script src="Scripts/knockout-2.2.1.js"></script>
</head>

Then I have written following code for HTML

<div>
    <h1>Knockout demo with asp.net web forms and asp.net webapi</h1>
</div>
<table >
    <thead>
        <tr>
            <td>Employee Id</td>
            <td>First Name</td>
            <td>Last Name</td>
        </tr>
    </thead>
    <tbody data-bind="foreach: employees">
        <tr >
            <td data-bind="text: EmployeeId"></td>
            <td data-bind="text: FirstName"></td>
            <td data-bind="text: LastName"></td>
        </tr>
    </tbody>

</table>

Here you can see that I have create a simple HTML table where I have written data-bind attribute to some of the html tags. That is a way of knockout to tell this particular tag id find with text property of td and employee id property.

Then I have written following code for the java script.

var viewModel =
{
    employees: ko.observableArray([]),
}
$(document).ready(function () {
    $.ajax({
        url: "/api/Employee",
        contentType: "text/json",
        type: "GET",
        success: function (data) {
            $.each(data, function (index) {
                viewModel.employees.push(ToKnockOutObservable(data[index]));
            });
            ko.applyBindings(viewModel);
        },
        error: function (data) {
            alert("error occured");
        }
    });
    function ToKnockOutObservable(employee) {
        return {
            EmployeeId: ko.observable(employee.EmployeeId),
            FirstName: ko.observable(employee.FirstName),
            LastName: ko.observable(employee.LastName),
        };
    }
});

Here you can see that I have created a view model for employee in JavaScript which is necessary to bind html tags with view model with knockout.js. Here I have created employee as Observable arrays this is one of the ways of detecting changes in collection. You can find more information about at following link.

http://knockoutjs.com/documentation/observableArrays.html

Then document.ready function I have made ajax call to web api and get a data for that and then create a collection of employee model with ToKnockOutObservable function. At the end I have used ko.Applybinding method to apply binding in HTML Tag.

So we are done with coding let’s run this demo in browser like following. It’s works smoothly..

Browser demo with knockout,web api and asp.net web forms

That’s it. Hope you like it. Stay tuned for more..

Comments

  1. Thanks a lot it really simply and working example. Better example for 'GET' method.

    ReplyDelete

Post a Comment

Your feedback is very important to me. Please provide your feedback via putting comments.

Popular posts from this blog

How to create Rest API(Web API) with ASP.NET Core 1.0

Recently Microsoft has released ASP.NET Core 1.0 RC2, I am getting lots of request from readers that about creating Web API. So I thought it will be a good idea to write a blog post about how to create Rest API(Web API) with ASP.NET Core 1.0.

So let’s get started via creating an ASP.NET Core 1.0 Web Application like following.



Once you click on ASP.NET Web Application, It will ask whether you need to create Web Application or Web API application. We are going to Web API so I am going to select Web API Application like following. Please note that in ASP.NET Core 1.0 there is no separate libraries or DLLs required for creating web APIs. This is just a project template.



Now once you click on OK It will create a Web API application with default values controller and program.cs.  As you know Program.cs is now starting point for the ASP.NET Core 1.0 application so It contains all the required configuration and startup items. Following is a code for that.
using System.IO; using Microsoft.Asp…

How to use migration with Entity Framework Core

Entity framework core is  the lightweight, extensible and cross-platform version of Entity Framework. Before some time, Microsoft has Released a new version of Entity Framework RC2. I have written a couple of blog post about Entity framework code first migration earlier for Entity framework 6.0. So there was a couple of request coming for writing a blog post about Entity Framework Core RC2 migration. So I thought it will be a good idea to give an overview how database migration works in Entity Framework Core RC2. This post will cover a basic scenario where we are going to create the database with existing ASP.NET Identity migration and then we are going to create a new model and have that migration applied in the database.

How to use Entity Framework Migrations: Let’s get started, To demonstrate entity framework core migrations, I am going to create a sample asp.net core web application like following.



Once we select asp.net core application it will appear the following dialog.



Now w…

Creating PDF with ASP.Net MVC and RazorPDF

Update: I have written a new blog post about better approach to create a PDF with asp.net mvc- You can find that following location.- A Better Solution to create PDF with Rotativa and ASP.NET MVC
In this post we are going to learn how we can easily create PDF from ASP.Net application with the help of Razor PDF NuGet package.

About Razor PDF:
This NuGet package is created by Al Nyveldt It internally uses ITextSharp an open source PDF convertor library. RazorPDF uses Razor View engine to create iTextXML which is in tern used to produce PDF file. You can get more information about that at below link.

https://www.nuget.org/packages/RazorPDF

Example(Creating PDF with ASP.Net MVC):
So what we are we waiting for ? Let’s create a simple example. To create example first thing we need to a create and ASP.Net MVC application.