Bước 1: Tạo Model với tên Book
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MVCTest07.Models
{
public class Book
{
public int Id { get; set; }
public string Name { get; set; }
public string Author { get; set; }
public decimal Price { get; set; }
public DateTime Published { get; set; }
}
}
Bước 2: Cài đặt Entity Framework
- Vào Tool/NuGet Pakage Manager/Manage NuGet Package for Solution... và cài đặt Entity Framework.
Bước 3: Tạo thư mục Context và lớp BookContext
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace MVCTest07.Context
{
public class BookContext:DbContext
{
public DbSet<Book> Books { get; set; }
}
}
Bước 4: Tạo chuỗi kết nối trong web.config
<connectionStrings>
<add name="BookContext" connectionString="Data Source=DAOTUONGSO\SQLEXPRESS; Initial Catalog=LibraryDB2155;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
Bước 5: Tạo Controller với lựa chọn Entity Framework
Bước 6: Hiệu chỉnh view Index
@model IEnumerable<MVCTest07.Models.Book>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<table>
<tr>
<td><a href='@Url.Action("Create","Books")' class="pull-right btn mauxanh btn-create"><i class="glyphicon glyphicon-plus"></i> New</a></td>
</tr>
</table>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Author)
</th>
<th>
@Html.DisplayNameFor(model => model.Price)
</th>
<th>
@Html.DisplayNameFor(model => model.Published)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Author)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
<td>
@Html.DisplayFor(modelItem => item.Published)
</td>
<td>
<a href='@Url.Action("Edit", "Books", routeValues: new { id=item.Id})' class="btn btn-xs mauvang btn-edit"><i class="glyphicon glyphicon-pencil"></i></a> <a href='@Url.Action("Delete", "Books", routeValues: new { id=item.Id})' class="btn btn-xs maudo btn-delete"><i class="glyphicon glyphicon-trash"></i></a> </td> </tr> } </table> <!-- Modal Create--> <div class="modal fade" id="myModalcreate" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <!-- modal content --> ... </div> </div> <script> $(document).ready(function () { $('.btn-create').click(function (e) { e.preventDefault(); var $modal = $('#myModalcreate'); var $modalDialog = $('.modal-dialog'); var href = $(this).prop('href'); // không cho phép tắt modal khi click bên ngoài modal var option = { backdrop: 'static' }; // load modal $modalDialog.load(href, function () { $modal.modal(option, 'show'); }); }); }); </script> <!-- Modal Edit--> <div class="modal fade" id="myModaledit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <!-- modal content --> ... </div> </div> <script> $(document).ready(function () { $('.btn-edit').click(function (e) { e.preventDefault(); var $modal = $('#myModaledit'); var $modalDialog = $('.modal-dialog'); var href = $(this).prop('href'); // không cho phép tắt modal khi click bên ngoài modal var option = { backdrop: 'static' }; // load modal $modalDialog.load(href, function () { $modal.modal(option, 'show'); }); }); }); </script> <!-- Modal Delete--> <div class="modal fade" id="myModaldelete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <!-- modal content --> ... </div> </div> <script> $(document).ready(function () { $('.btn-delete').click(function (e) { e.preventDefault(); var $modal = $('#myModaldelete'); var $modalDialog = $('.modal-dialog'); var href = $(this).prop('href'); // không cho phép tắt modal khi click bên ngoài modal var option = { backdrop: 'static' }; // load modal $modalDialog.load(href, function () { $modal.modal(option, 'show'); }); }); }); </script>
Bước 7: Hiệu chỉnh Controller
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using MVCCodeFirst.Context;
using MVCCodeFirst.Models;
namespace MVCCodeFirst.Controllers
{
public class BooksController : Controller
{
private BookContext db = new BookContext();
// GET: Books
public ActionResult Index()
{
return View(db.Books.ToList());
}
// GET: Books/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Book book = db.Books.Find(id);
if (book == null)
{
return HttpNotFound();
}
return View(book);
}
// GET: Books/Create
public ActionResult Create()
{
return PartialView();
}
// POST: Books/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Name,Author,Price,Published")] Book book)
{
if (ModelState.IsValid)
{
db.Books.Add(book);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(book);
}
// GET: Books/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Book book = db.Books.Find(id);
if (book == null)
{
return HttpNotFound();
}
return PartialView(book);
}
// POST: Books/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Name,Author,Price,Published")] Book book)
{
if (ModelState.IsValid)
{
db.Entry(book).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(book);
}
// GET: Books/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Book book = db.Books.Find(id);
if (book == null)
{
return HttpNotFound();
}
return PartialView(book);
}
// POST: Books/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Book book = db.Books.Find(id);
db.Books.Remove(book);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
Bước 8: Hiệu chỉnh view Create, Edite và Delete
//Hiệu chỉnh view Create
@model MVCCodeFirst.Models.Book
@{
ViewBag.Title = "Create";
}
@using (Html.BeginForm("Create", "Books", FormMethod.Post, htmlAttributes: new { @class = "form-create" }))
{
@Html.AntiForgeryToken()
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Add Item</h4>
</div>
<div class="modal-body">
<div class="form-horizontal">
<h4>Book</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Author, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Author, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Author, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Price, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Price, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Price, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Published, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Published, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Published, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn mauxanh"><i class="glyphicon glyphicon-floppy-save"></i> Add</button>
<button type="button" class="btn mauxam" data-dismiss="modal"><i class="glyphicon glyphicon-remove"></i> Close</button>
</div>
</div>
}
//Hiệu chỉnh view Edit
@model MVCCodeFirst.Models.Book
@{
ViewBag.Title = "Edit";
}
@using (Html.BeginForm("Edit", "Books", FormMethod.Post, htmlAttributes: new { @class = "form-edit" }))
{
@Html.AntiForgeryToken()
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Edit Item</h4>
</div>
<div class="modal-body">
<div class="form-horizontal">
<h4>Book</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.Id)
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Author, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Author, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Author, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Price, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Price, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Price, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Published, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Published, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Published, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn mauxanh"><i class="glyphicon glyphicon-floppy-save"></i> Update</button>
<button type="button" class="btn mauxam" data-dismiss="modal"><i class="glyphicon glyphicon-remove"></i> Close</button>
</div>
</div>
}
//Hiệu chỉnh view Delete
@model MVCCodeFirst.Models.Book
@{
ViewBag.Title = "Delete";
}
@using (Html.BeginForm("Delete", "Books", FormMethod.Post, htmlAttributes: new { @class = "form-create" }))
{
@Html.AntiForgeryToken()
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Delete Item</h4>
</div>
<div class="modal-body">
<h3>Are you sure you want to delete this?</h3>
</div>
<div class="modal-footer">
<button type="submit" class="btn mauxanh"><i class="glyphicon glyphicon-floppy-save"></i> Delete</button>
<button type="button" class="btn mauxam" data-dismiss="modal"><i class="glyphicon glyphicon-remove"></i> Close</button>
</div>
</div>
}