Skip to content

Instantly share code, notes, and snippets.

@KalinovDmitri
Created April 23, 2018 23:29
Show Gist options
  • Save KalinovDmitri/2f4da93ed79d0cc10237bfccd24d3cb9 to your computer and use it in GitHub Desktop.
Save KalinovDmitri/2f4da93ed79d0cc10237bfccd24d3cb9 to your computer and use it in GitHub Desktop.
MyBooks
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.HtmlControls;
using Newtonsoft.Json;
using MyBooks.Models;
using MyBooks.ViewModels;
namespace MyBooks.Controllers
{
public class BookController : Controller
{
BookContext db = new BookContext();
[HttpGet]
public async Task<ActionResult> MyBooks()
{
var query = db.Books
.OrderBy(x => x.Author).ThenBy(x => x.Name)
.Select(x => new BookViewModel
{
Id = x.Id,
Name = x.Name,
Author = x.Author,
Year = x.Year
});
var books = await query.ToListAsync();
return View(books);
}
[HttpPost]
public async Task<ActionResult> Add(BookViewModel bookModel)
{
var newBook = new Book
{
Name = bookModel.Name,
Author = bookModel.Author,
Year = bookModel.Year
};
try
{
db.Books.Add(newBook);
await db.SaveChangesAsync();
return Json(new BookViewModel
{
Id = newBook.Id,
Name = newBook.Name,
Author = newBook.Author,
Year = newBook.Year
}, JsonRequestBehavior.AllowGet);
}
catch (Exception exc)
{
// log exception
return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
}
}
[HttpPost]
public async Task<ActionResult> Delete(int id)
{
Book bookToRemove = new Book
{
Id = id // MAGIC step 1
};
try
{
db.Books.Attach(bookToRemove);
db.Entry(bookToRemove).State = EntityState.Deleted; // MAGIC step 2
await db.SaveChangesAsync();
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
catch (Exception exc)
{
// log exception
return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
}
}
}
}
@model IEnumerable<MyBooks.ViewModels.BookViewModel>
@{
ViewBag.Title = "MyBooks";
}
<style type="text/css">
.delete-book-link {
}
</style>
<div style="text-align: center">
<h3>My Books</h3>
</div>
<div>
<form id="addBookForm" method="post">
<div style="float: left; padding-right:10px;">
<table>
<tr>
<td><p>Enter book's name: </p></td>
<td>
<input id="bookName" name="Name" type="text" />
</td>
</tr>
<tr>
<td><p>Enter author's name: </p></td>
<td>
<input id="bookAuthor" name="Author" type="text" />
</td>
</tr>
<tr>
<td><p>Enter year of presentation: </p></td>
<td>
<input id="bookYear" name="Year" type="number" value="@DateTime.Now.Year" />
</td>
</tr>
<tr>
<td>
<a id="addBookButton" href="@Url.Action("Add", "Book")" class="btn btn-primary">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
<span><strong>Add</strong></span>
</a>
</td>
<td></td>
</tr>
</table>
</div>
</form>
<div id="result" style="width: 600px; height: 600px; overflow: scroll; border: solid 1px black;">
<table id="booksContainer">
<tr>
<td><p style="margin-right: 75px">Name</p></td>
<td><p style="margin-right: 75px">Author</p></td>
<td><p style="margin-right: 75px">Year</p></td>
<td></td>
</tr>
@foreach (var book in Model)
{
<tr>
<td><p>@book.Name</p></td>
<td><p>@book.Author</p></td>
<td><p>@book.Year</p></td>
<td>
<a href="@Url.Action("Delete", "Book", new { id = book.Id })" class="btn btn-primary delete-book-link">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
<span><strong>Delete</strong></span>
</a>
</td>
</tr>
}
</table>
</div>
</div>
@Scripts.Render("~/scripts/jquery-1.10.2.min.js")
@Scripts.Render("~/scripts/jquery.unobtrusive-ajax.min.js")
@section Scripts {
<script type="text/javascript">
$(document).ready(function () {
$("#addBookButton").click(addBook);
$("#booksContainer a.delete-book-link").click(deleteBook);
});
function toParagraphInHtml(e) {
if (e === undefined) {
return "";
}
return "<p>" + e.toString() + "</p>";
}
function handleAddingSuccess (e) {
var booksTable = document.getElementById("booksContainer");
var newBookRow = booksTable.insertRow(1);
newBookRow.insertCell(0).innerHTML = toParagraphInHtml(e.Name);
newBookRow.insertCell(1).innerHTML = toParagraphInHtml(e.Author);
newBookRow.insertCell(2).innerHTML = toParagraphInHtml(e.Year);
var deleteLink = document.createElement("a");
deleteLink.href = "/Book/Delete/" + e.Id.toString();
deleteLink.setAttribute("class", "btn btn-primary delete-book-link");
var glyph = document.createElement("span");
glyph.setAttribute("class", "glyphicon glyphicon-remove");
glyph.setAttribute("aria-hidden", "true");
var textSpan = document.createElement("span"),
text = document.createElement("strong");
text.innerText = "Delete";
textSpan.appendChild(text);
deleteLink.appendChild(glyph);
deleteLink.appendChild(textSpan);
var controlCell = newBookRow.insertCell(3);
controlCell.appendChild(deleteLink);
}
function addBook(e) {
var link = $(this);
e.preventDefault();
var addingForm = $("#addBookForm").first();
var serializedValues = addingForm.serializeArray();
var formData = {};
$.each(serializedValues, function (idx, val) {
formData[val.name] = val.value;
});
var requestUrl = e.currentTarget.href;
var request = $.ajax({
method: "POST",
url: requestUrl,
data: formData
});
request.done(function (res) {
var formElement = document.getElementById("addBookForm");
if (formElement !== undefined && formElement.reset !== undefined) {
formElement.reset();
}
handleAddingSuccess(res);
});
request.fail(function () {
alert ("Oops, something went wrong...");
});
}
function deleteBook(e) {
var link = $(this);
e.preventDefault();
var userConfirm = confirm("Do you really want to delete this book?");
if (userConfirm == true) {
var requestUrl = e.currentTarget.href;
var request = $.ajax({
method: "POST",
url: requestUrl,
});
request.done(function () {
link.parents("tr").fadeTo(300, 0, function () {
$(this).remove();
});
});
request.fail(function () {
alert ("Oops, something went wrong...");
});
}
}
</script>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment