var booksUri = '/api/books/'; var authorsUri = '/api/authors/'; function ajaxHelper(uri, method, data) {//Envía y/o recibe los datos de acuerdo a la URL, el método y los datos proporcionados. $('#error').html(''); return $.ajax({ type: method, url: uri, dataType: 'json', contentType: 'application/json', data: data ? JSON.stringify(data) : null }).fail(function (jqXHR, textStatus, errorThrown) { $('#error').html(errorThrown); }); } function getAuthors() { ajaxHelper(authorsUri, 'GET').done(function (data) { ImprimeAutores(data); }); } function getAllBooks() { ajaxHelper(booksUri, 'GET').done(function (data) { ImprimeLista(data); }); } function ImprimeAutores(jsondata) { var authors = $('#AuthorId'); // Limpia la lista de autores $(authors).empty(); $.each(jsondata, function (i, obj) { $(authors).append($('')); }); } function ImprimeLista(jsondata) { var books = $('#books'); var plantilla = $('#books li:first').clone(); // Limpia la lista de libros $(books).empty(); $.each(jsondata, function (i, obj) { var book = plantilla.clone(); $(book).find('.AuthorName').text(obj.AuthorName); $(book).find('.Title').text(obj.Title); $(book).find('a').click(function () { ajaxHelper(booksUri + obj.Id, 'GET').done(function (data) { ImprimeDetalle(data); }); }); $(book).appendTo(books); }); } function ImprimeDetalle(obj) { var tabladetalle = $('.table-details'); $(tabladetalle).find('.AuthorName').text(obj.AuthorName); $(tabladetalle).find('.Title').text(obj.Title); $(tabladetalle).find('.Year').text(obj.Year); $(tabladetalle).find('.Genre').text(obj.Genre); $(tabladetalle).find('.Price').text(obj.Price); } function addBook() { var book = { AuthorId: $('#AuthorId').val(), Genre: $('#inputGenre').val(), Price: $('#inputPrice').val(), Title: $('#inputTitle').val(), Year: $('#inputYear').val() }; ajaxHelper(booksUri, 'POST', book).done(function (item) { getAllBooks(); }); return false; } // Fetch the initial data. getAllBooks(); getAuthors();