ASP. NET web API & backbone (1) -- web API & simple get

Source: Internet
Author: User
This series describes how to use backbone to build a client Based on ASP. NET Web APIs (focusing on the use of backbone)

ASP. NET web API in. Net 4.5 allows us to quickly build restful service applications. With the powerful client framework backbone, we can adopt the MVC design idea,
Organize JavaScript modules (functions) on the client side to achieve fast and flexible application development.

For introduction to ASP. NET Web APIs, refer to my blog: [ASP. NET] web API (. NET 4.5)
About backbone, You can first look at the official introduction: http://backbonejs.org/

[Server web API]
I designed a simple application: Message book
The first is the server 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 { }        }    }}

Of course, we need to add, delete, modify, and query, so we have the following repository interface.

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);    }}

The specific implementation adopts Memory Data Storage:

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;        }    }}

Use ninject to inject data during webapi initialization (initialdata is a subclass of dictionarycommentrepository and some initial data is added to the constructor)

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 is the implementation class of Web APIs and implements a simple 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    }}

After the release, use fiddler for testing (do not forget to add the accept: Application/JSON header so that data in JSON format will be returned)

[Client]
Add backbone first. You can download it on the official website or directly use nuget: Install-package backbone. js.
The following html provides a preliminary understanding of backbone:
This "Guestbook" is defined as "commentmodel" and "commentview". "View" is responsible for page profiling, and "model" is the corresponding server entity. "model. Fetch" gets data, and "view. Render" delivers the obtained data
The template of underscore generates HTML results. For other details, see the comments in the following code.

<! Doctype HTML> 

Running result:

The following describes in detail how backbone calls webapi crud.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.