這個系列主要介紹如何使用Backbone搭建基於 ASP.NET Web API 的用戶端(重點在於Backbone的使用)
.NET 4.5 中的 ASP.NET Web API 使得我們可以快速搭建基於REST風格的服務應用,利用強大的用戶端架構 Backbone 我們可以採用MVC的設計思路,
組織用戶端Javascript模組(功能) 從而實現快速靈活的應用開發。
關於 ASP.NET Web API 的介紹,可以看我這篇部落格:【ASP.NET】 Web Api (.NET 4.5)
關於 Backbone ,可以先看看官方介紹:http://backbonejs.org/
【服務端 Web API】
為了示範我設計了一個簡單的應用:留言簿
首先是服務端的 Model:
namespace BackboneAndWebApi.Models{ public class Comment { public Comment() { } public Comment(string text, string author) { Text = text; Author = author; } public int ID { get; set; } [Required] public string Text { get; set; } [Required] [StringLength(10, ErrorMessage = "Author is too long! This was validated on the server.")] public string Author { get; set; } [Required] public string Email { get; set; } public string GravatarUrl { get { return HttpUtility.HtmlDecode(Gravatar.GetUrl(Email ?? "", 40, defaultImage: "retro", rating: GravatarRating.G)); } set { } } }}
當然要有增刪改查,於是有了下面的 Repository 介面
namespace BackboneAndWebApi.Models{ public interface ICommentRepository { IEnumerable<Comment> Get(); bool TryGet(int id, out Comment comment); Comment Add(Comment comment); bool Delete(int id); bool Update(Comment comment); }}
具體實現採用記憶體資料存放區:
namespace BackboneAndWebApi.Models{ public class DictionaryCommentRepository : ICommentRepository { int nextID = 0; Dictionary<int, Comment> comments = new Dictionary<int, Comment>(); public IEnumerable<Comment> Get() { return comments.Values.OrderBy(comment => comment.ID); } public bool TryGet(int id, out Comment comment) { return comments.TryGetValue(id, out comment); } public Comment Add(Comment comment) { comment.ID = nextID++; comments[comment.ID] = comment; return comment; } public bool Delete(int id) { return comments.Remove(id); } public bool Update(Comment comment) { bool update = comments.ContainsKey(comment.ID); comments[comment.ID] = comment; return update; } }}
利用 Ninject 在 WebAPI 初始化時注入(InitialData 是 DictionaryCommentRepository 的子類,建構函式中加一些初始資料)
namespace BackboneAndWebApi{ public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Filters.Add(new ValidateAttribute()); IKernel kernel = new StandardKernel(); kernel.Bind<ICommentRepository>().ToConstant(new InitialData()); config.DependencyResolver = new NinjectResolver(kernel); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } }}
CommentsController 是 Web API 的實作類別,實現了簡單的GET
namespace BackboneAndWebApi.Controllers{ public class CommentsController : ApiController { ICommentRepository repository; public CommentsController(ICommentRepository repository) { this.repository = repository; } #region GET [Queryable] public IQueryable<Comment> GetComments() { return repository.Get().AsQueryable(); } public Comment GetComment(int id) { Comment comment; if (!repository.TryGet(id, out comment)) throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound)); return comment; } #endregion }}
發布後,用Fiddler測試(別忘記加上 Accept: application/json 的Header,這樣才會返回json格式的資料)
【用戶端】
先加入 Backbone,可以上官網自己下載,或者直接用 Nuget : Install-Package Backbone.js
通過下面的 HTML 可以對 Backbone 進行初步的理解:
這個“留言簿” 定義為 CommentModel 和 CommentView,View負責頁面的描繪,Model則是對應服務端實體,model.fetch 取得資料,view.render 將取到的資料交給
underscore 的 template 產生HTML結果。其他一些細節請看下面代碼中的注釋。
<!DOCTYPE html><html><head> <meta charset="utf-8" /> <title>Comments Test Home Page</title> <link href="/Content/Demo.css" rel="stylesheet" type="text/css" /> <script src="Scripts/jquery-1.9.0.min.js"></script> <script src="Scripts/underscore-1.4.3.js"></script> <script src="Scripts/backbone-0.9.9.js"></script></head><body> <nav> <div class="demo-navigation"> <a href="default.htm"><<< Back</a> | Demo 1 Simple Get | <a href="demo2-crud.htm">On to Demo 2 - Simple CRUD >>></a> </div> </nav> <div id="content"> <div id="demo-actions"> <div> <legend>Get Comments Demos</legend> <button id="getComments">Go!</button> </div> </div> <div id="article"> <p> This first demo shows a very simple GET scenario. Click on the button to use jQuery to retrieve JSON data from a Web API endpoint and then display the contents of that payload in the UI. </p> <p> The code represents retrieving data in a manner that any developer familiar with jQuery would understand. </p> </div> <ul id="comments"> </ul> <!-- 模板 --> <script id="commentTemplate" type="text/html"> <% _.each(comments, function(item) { %> <li class="comment"> <header> <div class="info"> <img src='<%= item.GravatarUrl %>' /> <strong><span><%= item.Author %></span></strong> </div> </header> <div class="body"> <p><%= item.Text %></p> </div> </li> <% }); %> </script> <script type="text/javascript"> var CommentModel = Backbone.Model.extend({ // model 對應服務端的API URL url: 'api/comments' }); var CommentView = Backbone.View.extend({ // 將body作為一個View el: 'body', // 載入模板 template: _.template($('#commentTemplate').html()), // 綁定HTML上"Go!"按鈕,調用 model.fetch 擷取資料 // model.fetch 會調用 Backbone.sync('read', model, options) 裡面封裝了ajax events: { 'click #getComments': function () { this.model.fetch(); } }, initialize: function () { this.model.on('change', this.render, this); }, render: function () { var data = this.model.toJSON(); $('#comments').html(this.template({ comments: data })); return this; } }); $(function () { var view = new CommentView({ model: new CommentModel() }); }); </script> </div></body></html>
運行結果:
下面將詳細介紹 Backbone 是如何調用 WebApi 的CRUD。