/// <summary> /// 书存储库接口 /// </summary> public interface IBookRepository { /// <summary> /// 书模型集合 /// </summary> IQueryable<Book> Books { get; } /// <summary> /// 保存书 /// </summary> /// <param></param> /// <returns></returns> int SaveBook(Book book); /// <summary> /// 删除书 /// </summary> /// <param></param> /// <returns></returns> Book DeleteBook(int id); }
EfBookRepository.cs
/// <summary> /// 书存储库 /// </summary> public class EfBookRepository : IBookRepository { private readonly EfDbContext _context = new EfDbContext(); /// <summary> /// 书模型集合 /// </summary> public IQueryable<Book> Books => _context.Books; /// <summary> /// 保存书 /// </summary> /// <param></param> /// <returns></returns> public int SaveBook(Book book) { if (book.Id == 0) { _context.Books.Add(book); } else { var model = _context.Books.Find(book.Id); if (model==null) { return 0; } model.Category = book.Category; model.Description = book.Description; model.Name = book.Name; model.Price = book.Price; } return _context.SaveChanges(); } /// <summary> /// 删除书 /// </summary> /// <param></param> /// <returns></returns> public Book DeleteBook(int id) { var model = _context.Books.Find(id); if (model == null) { return null; } _context.Books.Remove(model); _context.SaveChanges(); return model; } }
需要对 Book 模型加上验证用的特性:
[Table("Book")] public class Book { /// <summary> /// 标识 /// </summary> public int Id { get; set; } /// <summary> /// 名称 /// </summary> [Required(ErrorMessage = "名称不能为空")] public string Name { get; set; } /// <summary> /// 描述 /// </summary> [Required(ErrorMessage = "描述不能为空")] public string Description { get; set; } /// <summary> /// 价格 /// </summary> [Required(ErrorMessage = "价格不能为空")] [Range(0.01, double.MaxValue, ErrorMessage = "请填写合适的价格")] public decimal Price { get; set; } /// <summary> /// 分类 /// </summary> [Required(ErrorMessage = "分类不能为空")] public string Category { get; set; } }
_AdminLayout.cshtml 需要引入验证用的 js(客户端验证):
<script src="https://www.jb51.net/~/Scripts/jquery-1.10.2.js"></script> <script src="https://www.jb51.net/~/Scripts/jquery.validate.js"></script> <script src="https://www.jb51.net/~/Scripts/jquery.validate.unobtrusive.js"></script>
Edit.cshtml
@model Wen.BooksStore.Domain.Entities.Book @{ Layout = "~/Views/Shared/_AdminLayout.cshtml"; } <h2>编辑</h2> <div> @Html.ValidationSummary() <div> @using (Html.BeginForm()) { @Html.HiddenFor(x => x.Id) <table> <tr> <td>名称</td> <td>@Html.TextBoxFor(x => x.Name)</td> </tr> <tr> <td>价格</td> <td>@Html.TextBoxFor(x => x.Price)</td> </tr> <tr> <td>分类</td> <td>@Html.TextBoxFor(x => x.Category)</td> </tr> <tr> <td>描述</td> <td>@Html.TextAreaFor(x => x.Description)</td> </tr> </table> <input type="submit" value="提交" /> } </div> </div>
图:错误提示
删除
/// <summary> /// 删除 /// </summary> /// <param></param> /// <returns></returns> [HttpPost] public ActionResult Delete(int id) { _bookRepository.DeleteBook(id); return RedirectToAction("Index"); }
加入提示,我们在新增、编辑和删除时应该加入必要的提示信息,使用TempData。
/Admin/Index.cshtml 下的也要添加:
执行效果: