ASP.NET MVC 4 – Unity.Mvc4 + AutoMapper + Entity Framework 5 ( List / Insert / Edit / Delete Record ) + View + Model ( EditorTemplates + Form Validation ) 方法
( Project : ProductServiceLibrary ) INewsRepository.cs |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProductServiceLibrary { public interface INewsRepository { IEnumerable<News> GetAll(); News Get(int id); void Add(News news); void Edit(News news); void Delete(int id); } } |
( Project : ProductServiceLibrary ) NewsRepository.cs |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProductServiceLibrary { public class NewsRepository : INewsRepository { private List<News> news; private BIProductEntities entity; public NewsRepository() { entity = new BIProductEntities(); news = entity.News.OrderByDescending(x => new { x.News_Date }).ToList(); } public IEnumerable<News> GetAll() { return news.ToList(); } public News Get(int id) { return news.Find(p => p.News_ID == id); } public void Add(News news) { entity = new BIProductEntities(); news.News_Date = System.DateTime.Now; entity.News.Add(news); entity.SaveChanges(); } public void Edit(News newsitem) { News item = news.Find(p => p.News_ID == newsitem.News_ID); if(item != null){ item.News_Date = System.DateTime.Now; item.News_Name = newsitem.News_Name; item.News_Content = newsitem.News_Content; entity.SaveChanges(); } } public void Delete(int id) { News item = this.Get(id); if (item != null) { entity.News.Remove(item); entity.SaveChanges(); } } } } |
( Project : MVCApplication ) AutoMapperConfig.cs |
using System; using System.Collections.Generic; using AutoMapper; using ProductServiceLibrary; namespace MvcApplication { public class AutoMapperConfig { public static void Configure() { … … Mapper.CreateMap<ProductServiceLibrary.News, Models.News>().ReverseMap(); Mapper.AssertConfigurationIsValid(); } } } |
( Project : MVCApplication ) Bootstrapper.cs |
using System.Web.Mvc; using Microsoft.Practices.Unity; using Unity.Mvc4; using ProductServiceLibrary; namespace MvcApplication { public static class Bootstrapper { public static IUnityContainer Initialise() { var container = BuildUnityContainer(); DependencyResolver.SetResolver(new UnityDependencyResolver(container)); return container; } private static IUnityContainer BuildUnityContainer() { var container = new UnityContainer(); … … container.RegisterType<INewsRepository, NewsRepository>(); RegisterTypes(container); return container; } public static void RegisterTypes(IUnityContainer container) { } } } |
( Project : MvcApplication ) Global.asax.cs |
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace MvcApplication { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterAuth(); Bootstrapper.Initialise(); AutoMapperConfig.Configure(); } } } |
( Project : MVCApplication ) \Models\News.cs |
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Globalization; using System.Web.Security; namespace MvcApplication.Models { public class News { [Key] [Required] public int News_ID { get; set; } [Display(Name="News Header")] [Required(ErrorMessage = "News Header Required")] public string News_Name { get; set; } [Display(Name = "News Content")] [Required(ErrorMessage = "News Content Required")] public string News_Content { get; set; } [Required] public System.DateTime News_Date { get; set; } } } |
( Project : MVCApplication ) \Controllers\NewsController.cs |
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using ProductServiceLibrary; using AutoMapper; using MvcApplication.Models; namespace MvcApplication.Controllers { public class NewsController : Controller { readonly INewsRepository repository; public NewsController(INewsRepository repository) { this.repository = repository; } public ActionResult Index() { var model = Mapper.Map(repository.GetAll().ToList(), new List<Models.News>()); return View(model); } public ActionResult Detail(int? id) { if(id.HasValue){ var model = Mapper.Map(repository.Get(id.Value), new Models.News()); return View(model); }else{ return RedirectToAction("Index"); } } public ActionResult Add() { return View("Edit"); } [HttpPost] public ActionResult Add(Models.News News) { if (ModelState.IsValid) { repository.Add(Mapper.Map(News, new ProductServiceLibrary.News())); } return RedirectToAction("Index"); } public ActionResult Edit(int? id) { if(id.HasValue){ return View(Mapper.Map(repository.Get(id.Value), new Models.News())); }else{ return RedirectToAction("Index"); } } [HttpPost] public ActionResult Edit(Models.News News) { if (ModelState.IsValid) { repository.Edit(Mapper.Map(News, new ProductServiceLibrary.News())); } return RedirectToAction("Index"); } public ActionResult Delete(int? id) { if (id.HasValue) repository.Delete(id.Value); return RedirectToAction("Index"); } } } |
( Project : MVCApplication ) \Views\News\Index.cshtml |
@model List<MvcApplication.Models.News> @{ <style> #NewsList th, #NewsList td{ height:27px; font-size:17px; cursor:default; } #NewsList { margin-bottom: 20px; } </style> } <table id="NewsList" border="0" cellpadding="0" cellspacing="0" width="100%"> <tr> <th colspan="3"> </th> <th>ID</th> <th>Title</th> <th>Date</th> </tr> @foreach (MvcApplication1.Models.News item in Model) { <tr> <td>@Html.ActionLink("DELETE", "Delete", new { id = item.News_ID }, new { style = "text-decoration:none; font-weight:bold;" })</td> <td>@Html.ActionLink("SELECT", "Detail", new { id = item.News_ID }, new { style = "text-decoration:none; font-weight:bold;" })</td> <td>@Html.ActionLink("EDIT", "Edit", new { id = item.News_ID }, new { style = "text-decoration:none; font-weight:bold;" })</td> <td>@(item.News_ID)</td> <td>@(item.News_Name)</td> <td>@(item.News_Date)</td> </tr> } </table> @Html.ActionLink("INSERT", "Add", null, new { style = "font-size:17px; text-decoration:none; font-weight:bold;" }) |
( Project : MVCApplication ) \Views\News\Detail.cshtml |
@model MvcApplication.Models.News <div style="margin-top:15px;"> <span style="font-size:25px; line-height:22px;">@(Model.News_Name)</span> <span style="font-size:13px; line-height:22px;">@(Model.News_Date)</span> </div> <div style="font-size:16px; line-height:21px; margin-top:20px; margin-bottom:25px;"> @Html.Raw(Html.Encode(Model.News_Content).Replace("\n", "<br />")) </div> @Html.ActionLink("Return To News", "Index", null, new { style = "margin:0px 0px 0px 0px; padding:0px 0px 0px 0px; font-size:15px;"}) |
( Project : MVCApplication ) \Views\News\Edit.cshtml |
@model MvcApplication.Models.News <style> input.input-validation-error, textarea.input-validation-error { border: 1px solid #e80c4d; } </style> @if(Model != null){ using (Html.BeginForm("Edit", "News")) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) @Html.EditorForModel("EditNews") } } else { using (Html.BeginForm("Add", "News")) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) @Html.EditorForModel("AddNews") } } <div> @Html.ActionLink("Back to List", "Index") </div> @section Scripts { @Scripts.Render("~/bundles/jqueryval") } |
( Project : MVCApplication ) \Views\Shared\EditorTemplates\AddNews.cshtml |
@model MvcApplication.Models.News <fieldset> <legend>News</legend> <div class="editor-label"> @Html.LabelFor(model => model.News_Name) </div> <div class="editor-field"> @Html.TextBoxFor(model => model.News_Name, null, new { style = "width:100%;" }) @Html.ValidationMessageFor(model => model.News_Name) </div> <div class="editor-label"> @Html.LabelFor(model => model.News_Content) </div> <div class="editor-field"> @Html.TextAreaFor(model => model.News_Content, new { style = "width:100%;", rows = "10" }) @Html.ValidationMessageFor(model => model.News_Content) </div> <p> <input type="submit" value="Create" /> </p> </fieldset> |
( Project : MVCApplication ) \Views\Shared\EditorTemplates\EditNews.cshtml |
@model MvcApplication.Models.News <fieldset> <legend>News</legend> @Html.HiddenFor(model => model.News_ID) <div class="editor-label"> @Html.LabelFor(model => model.News_Name) </div> <div class="editor-field"> @Html.TextBoxFor(model => model.News_Name, null, new { style = "width:100%;" }) @Html.ValidationMessageFor(model => model.News_Name) </div> <div class="editor-label"> @Html.LabelFor(model => model.News_Content) </div> <div class="editor-field"> @Html.TextAreaFor(model => model.News_Content, new { style = "width:100%;", rows = "10" }) @Html.ValidationMessageFor(model => model.News_Content) </div> <p> <input type="submit" value="Save" /> </p> </fieldset> |