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.java
這篇文章咱們將見到如何使用 Knockout, ASP.Net Web API and ASP.Net 一塊兒順利工做。不少例子都是用 ASP.Net MVC, Web API 和 Knockout.js 一塊兒很好地工做。因此我認爲這是寫關於 ASP.Net Web API, ASP.NET Web Forms, Knockout.js 一塊兒工做而且咱們可使用Knockout.js建立簡單數據綁定的博客的好主題jquery
ASP.Net Web Forms:web
ASP.Net Web 表單:ajax
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.json
咱們都知道家ASP.Net Web Forms 是一個創建網站及應用程序的重要開發技術。ASP.Net 容許使用事件驅動模型建立動態網站。它是一個用最簡單的方法來建立應用程序和網站。api
ASP.Net Web API:數組
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.restful
ASP.Net Web API 是一個容許創建HTTP服務普遍用於包括瀏覽器和移動設備的客戶端的框架。它提供簡單的方法編寫RESTful HTTP服務。它能夠被全部類型的HTTP 協議的客戶端訪問。客戶端能夠跟據需求制定一個GET,PUT,POST 和DELETE 請求而且獲得適當的響應。
Knockout JS:
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.
按照 knockoutjs.com說明,Knockout 是一個JavaScript類庫,幫助你使用清晰的數據模型建立一個豐富的響應式顯示和編輯用戶界面。他提供一種聲明’Observable’方法把視圖模型綁定在瀏覽器上。
Getting Started with ASP.Net Web Forms and ASP.Net Web API:
開始使用ASP.Net Web Forms and ASP.Net 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.
咱們開始吧 首先咱們在Visual Studio2012建立一個空的Web應用程序。步驟爲文件->新建項目。
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.
如今一旦建立應用程序,Web API路由功能要求咱們須要添加 System.Web.Routing 引用。
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.
如今是時候建立一個模型類型用於WebAPI.如下是這個類的代碼。做爲剛剛建立的示例這是很基本的。因此爲這個類建立了3個屬性。
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.
如今,讓咱們爲建立的Web API添加Api 控制器類。
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.
如今是時候在ASP.Net Web API 員工控制器中寫代碼,如下是我寫好的代碼。
這裏有我建立的員工清單和寫好的GetEmployee方法。
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.
如今咱們的Web API準備好了,而且咱們須要添加API路由來處理請求。讓咱們首先添加全局應用程序類。
Now in application_start I have written following code to create a route for web api.
如今在application_Start裏,我建立了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
這裏有剛纔定義的 api/controller 路由。因此咱們的URL將會象這樣。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.
因此如今咱們的API差很少裝備好了。是時候經過NuGet包添加腳本了。咱們須要兩個JQuery腳本進得初始處理而且綁定AJAX調用和KnockoutJS。
same way for knockout.
Knockout也是一樣的方法。
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.
因此咱們準務寫JavaScript 的API調用代碼,而且執行Knockout綁定。讓咱們首先建立一個空白的Web表單和寫一些代碼。
Now first I have included both scripts in default.aspx head tag like following.
如今首先要包含兩個腳本在Default.aspx中的Head標籤中,像下面這樣。
<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
我編寫好的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.
這裏你會看到我建立的簡單的HTML表格,在哪裏有我寫的一些數據綁定屬性HTML標籤
Then I have written following code for the java script.
而後我寫入下面的 JavaScript代碼。
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
這裏你能夠看到我建立的員工視圖模型的JavaScript腳本,這裏必須在Knockout.js使用視圖模型進行HTML標籤綁定。這裏有我建立的用於觀察的員工數組,這是在集合中檢測變化的一種方法。你能夠在下面連接中找到更多的信息。
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.
[而後 document.ready 函數有我製造的AJAX調用Web API ,而且在ToKnockOutObservable函數中建立一個員工集合獲得數據。]最後,我用ko.Applybinding 方法應用綁定HTML標籤。
So we are done with coding let’s run this demo in browser like following. It’s works smoothly..
因此咱們完成代碼編寫,讓示例運行在瀏覽器中以下。它工做順利..
That’s it. Hope you like it. Stay tuned for more..
到此爲止。但願你喜歡。更多內容敬請期待..