一、添加分类管理
1.创建CRUD控制器
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using SportsStorePeta.Domain.Abstract;namespace SportsStorePeta.WebUI.Controllers{ public class AdminController : Controller { private IProductRepository _repository; public AdminController(IProductRepository repo) { _repository = repo; } public ViewResult Index() { return View(_repository.Products); } }}
2.创建新布局(_AdminLoyout.cshtml)
@ViewBag.Title @RenderBody()
新建Admin.CSS
body ,td { font-family: Segoe UI, Verdana;}h1 { padding: .5em;padding-top: 0;font-weight: bold; font-size: 1.5em;border-bottom: 2px solid gray;}div#content{ padding: .9em;}table.grid td,table.grid th { border-bottom: 1px dotted gray;text-align: left;}table.grid { border-collapse: collapse;width: 100%;}table.grid th.NumericCol,table.grid td.NumericCol { text-align: right;padding-right: 1em;}form{ margin-bottom: 0px;}div.Message { background: gray;color: white;padding: .2em;margin-top: .25em;}/* Styles for validation helpers-----------------------------------------------------------*/.field-validation-error { color: #f00;display: block;}.field-validation-valid { display: none;}.input-validation-error { border: 1px solid #f00; background-color: #ffeeee;}.validation-summary-errors { font-weight: bold; color: #f00;}.validation-summary-valid { display: none;}
3.实现List视图Admin/Index
@using SportsStorePeta.Domain.Entities@model IEnumerable@{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_AdminLoyout.cshtml";} Index
@Html.ActionLink("新建", "Create")
@foreach (Product item in Model) { @Html.DisplayNameFor(m => m.Name) @Html.DisplayNameFor(m => m.Description) @Html.DisplayNameFor(m => m.Price) @Html.DisplayNameFor(m => m.Category) } @Html.DisplayFor(modelItem => item.Name) @Html.DisplayFor(modelItem => item.Description) @Html.DisplayFor(modelItem => item.Price) @Html.DisplayFor(modelItem => item.Category) @Html.ActionLink("修改", "Edit", new {id = item.ProductId})| @Html.ActionLink("详细", "Details", new {id = item.ProductId})| @Html.ActionLink("删除","Delete",new{id=item.ProductId})
紧凑型视图:
@using SportsStorePeta.Domain.Entities@model IEnumerable@{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_AdminLoyout.cshtml";} 所有产品
@{ int i = 0;} @foreach (Product item in Model) { i = i + 1; 序号 名称 价格 删除 } @i @Html.ActionLink(item.Name, "Edit", new {item.ProductId}) @item.Price.ToString("C") @using (Html.BeginForm("Delete", "Admin")) { @Html.Hidden("ProductId", item.ProductId) } @Html.ActionLink("新建", "Create")
4.编辑产品
创建Edit动作方法
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using SportsStorePeta.Domain.Abstract;using SportsStorePeta.Domain.Entities;namespace SportsStorePeta.WebUI.Controllers{ public class AdminController : Controller { private IProductRepository _repository; public AdminController(IProductRepository repo) { _repository = repo; } public ViewResult Index() { return View(_repository.Products); } public ViewResult edit(int productId) { Product product = _repository.Products.FirstOrDefault(p => p.ProductId == productId); return View(product); } }}
创建Edit视图
@model SportsStorePeta.Domain.Entities.Product@{ ViewBag.Title = "Admin 编辑 "+@Model.Name; Layout = "~/Views/Shared/_AdminLoyout.cshtml";}编辑 @Model.Name
@using (Html.BeginForm()){ @Html.EditorForModel() @Html.ActionLink("取消并返回列表","Index")}
对ORM模型类添加注解属性:
[MetadataType(typeof(ProductMetaData))] public partial class Product : DbContextDB.Record{ ... }
添加Product类的注解属性类:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.ComponentModel.DataAnnotations;using System.Web.Mvc;namespace SportsStorePeta.Domain.Entities{ public partial class ProductMetaData { [HiddenInput(DisplayValue = false)] public int ProductId { get; set; } [Display(Name = "产品名称")] public string Name { get; set; } [DataType(DataType.MultilineText)] [Display(Name = "描述")] public string Description { get; set; } [Display(Name = "类别")] public string Category { get; set; } [Display(Name = "价格")] public decimal Price { get; set; } }}
添加CSS样式
.editor-field{ margin-bottom: .8em;}.editor-label{ font-weight: bold;}.editor-label:after{ content: ":"}.text-box{ width: 25em;}.multi-line { height: 5em;font-family: Segoe UI, Verdana;}
更新产品存储库
using System;using System.Collections.Generic;using System.Linq;using System.Text;using SportsStorePeta.Domain.Entities;namespace SportsStorePeta.Domain.Abstract{ public interface IProductRepository { IQueryableProducts { get; } void SaveProduct(Product product); }}
实现SaveProduct方法
using System;using System.Collections.Generic;using System.Linq;using System.Text;using SportsStorePeta.Domain.Abstract;using SportsStorePeta.Domain.Entities;namespace SportsStorePeta.Domain.Concrete{ public class PpProductRepository :IProductRepository { private readonly PpContext _context=new PpContext(); public IQueryableProducts { get { return _context.Products; } } public void SaveProduct(Product product) { _context.Save(product); //自动判断新增、修改 } }}
处理Edit的Post请求
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using SportsStorePeta.Domain.Abstract;using SportsStorePeta.Domain.Entities;namespace SportsStorePeta.WebUI.Controllers{ public class AdminController : Controller { private IProductRepository _repository; public AdminController(IProductRepository repo) { _repository = repo; } public ViewResult Index() { return View(_repository.Products); } public ViewResult Edit(int productId) { Product product = _repository.Products.FirstOrDefault(p => p.ProductId == productId); return View(product); } [HttpPost] public ActionResult Edit(Product product) { if (ModelState.IsValid) { _repository.SaveProduct(product); TempData["message"] = string.Format("{0} 已经保存。", product.Name); return RedirectToAction("Index"); } else { return View(product); } } }}
显示确认消息
@ViewBag.Title @if (TempData["message"] != null) {@TempData["message"]} @RenderBody()
添加模型验证
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.ComponentModel.DataAnnotations;using System.Web.Mvc;namespace SportsStorePeta.Domain.Entities{ public partial class ProductMetaData { [HiddenInput(DisplayValue = false)] public int ProductId { get; set; } [Display(Name = "产品名称")] [Required(ErrorMessage = "请输入产品名称")] public string Name { get; set; } [DataType(DataType.MultilineText)] [Display(Name = "描述")] [Required(ErrorMessage = "请输入产品描述")] public string Description { get; set; } [Display(Name = "类别")] [Required(ErrorMessage = "请指定产品类别")] public string Category { get; set; } [Display(Name = "价格")] [Required] [Range(0.01,Double.MaxValue,ErrorMessage = "请输入真实的价格")] public decimal Price { get; set; } }}
启用客户端验证
@ViewBag.Title @if (TempData["message"] != null) {@TempData["message"]} @RenderBody()
5.创建新产品
添加Create 动作方法
public ViewResult Create() { return View("Edit", new Product()); }
修改共用的Edit视图
@model SportsStorePeta.Domain.Entities.Product@{ ViewBag.Title = "Admin 编辑 "+@Model.Name; Layout = "~/Views/Shared/_AdminLoyout.cshtml";}编辑 @Model.Name
@using (Html.BeginForm("Edit","Admin")){ @Html.EditorForModel() @Html.ActionLink("取消并返回列表","Index")}
6.删除产品
接口添加删除方法
using System;using System.Collections.Generic;using System.Linq;using System.Text;using SportsStorePeta.Domain.Entities;namespace SportsStorePeta.Domain.Abstract{ public interface IProductRepository { ////// 获得产品集合 /// IQueryableProducts { get; } /// /// 产品信息修改保存 /// /// void SaveProduct(Product product); ////// 删除产品 /// /// ///Product DeleteProduct(int productId); }}
实体框架删除方法实现
using System;using System.Collections.Generic;using System.Linq;using System.Text;using SportsStorePeta.Domain.Abstract;using SportsStorePeta.Domain.Entities;namespace SportsStorePeta.Domain.Concrete{ public class PpProductRepository :IProductRepository { private readonly PpContext _context=new PpContext(); public IQueryableProducts { get { return _context.Products; } } public void SaveProduct(Product product) { _context.Save(product); //自动判断新增、修改 } public Product DeleteProduct(int productId) { Product dbProduct = _context.FirstOrDefault ("Where ProductId=@ProductId", new {ProductId = productId}); if (dbProduct != null) { _context.Delete (dbProduct); } return dbProduct; } }}
添加Delete动作方法
[HttpPost] public ActionResult Delete(int productId) { Product deleteProduct = _repository.DeleteProduct(productId); if (deleteProduct != null) { TempData["message"] = string.Format("{0} 已经被删除。", deleteProduct.Name); } return RedirectToAction("Index"); }
源码: 访问密码 65f3