这个系列主要介绍如何使用Backbone搭建基于 ASP.NET Web API 的客户端(重点在于Backbone的使用)
.NET 4.5 中的 ASP.NET Web API 使得我们可以快速搭建基于REST风格的服务应用,利用强大的客户端框架 Backbone 我们可以采用MVC的设计思路,
组织客户端Javascript模块(功能) 从而实现快速灵活的应用开发。
【服务端 Web API】
为了演示我设计了一个简单的应用:留言簿
首先是服务端的 Model:
[csharp]
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 { }
}
}
}
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 接口
[csharp]
namespace BackboneAndWebApi.Models
{
public inte易做图ce 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 inte易做图ce ICommentRepository
{
IEnumerable<Comment> Get();
bool TryGet(int id, out Comment comment);
Comment Add(Comment comment);
bool Delete(int id);
bool Update(Comment comment);
}
}具体实现采用内存数据存储:
[csharp]
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;
}