添加实体类模型文件
public class Album{public virtual int AlbumId { get; set; }public virtual int GenreId { get; set; }public virtual int ArtistId { get; set; }public virtual string Title { get; set; }public virtual decimal Price { get; set; }public virtual string AlbumArtUrl { get; set; }public virtual Genre Genre { get; set; }public virtual Artist Artist { get; set; }}
public class Artist{public virtual int ArtistId { get; set; }public virtual string Name { get; set; }}
public class Genre{public virtual int GenreId { get; set; }public virtual string Name { get; set; }public virtual string Description { get; set; }public virtual ListAlbums { get; set; }}
The DbContext Class
public class MusicStoreDB : DbContext
{ public DbSet<Album> Albums { get; set; }public DbSet<Genre> Genres { get; set; }public DbSet<Artist> Artists { get; set; }}LINQ语句查询方式
var db = new MusicStoreDB();var allAlbums = from album in db.Albumsorderby album.Title ascendingselect album;
The StoreManagerController控制器
public class StoreManagerController : Controller{private MusicStoreDB db = new MusicStoreDB();//// GET: /StoreManager/public ViewResult Index(){var albums = db.Albums.Include(a => a.Genre).Include(a => a.Artist);return View(albums.ToList());}
视图VIEW中遍历数据方式
@model IEnumerable@{ViewBag.Title = "Index";} Index
@Html.ActionLink("Create New", "Create")
@foreach (var item in Model) { @Html.DisplayNameFor(model => model.Genre.Name) @Html.DisplayNameFor(model => model.Artist.Name) @Html.DisplayNameFor(model => model.Title) @Html.DisplayNameFor(model => model.Price) @Html.DisplayNameFor(model => model.AlbumArtUrl) } @Html.DisplayFor(modelItem => item.Genre.Name) @Html.DisplayFor(modelItem => item.Artist.Name) @Html.DisplayFor(modelItem => item.Title) @Html.DisplayFor(modelItem => item.Price) @Html.DisplayFor(modelItem => item.AlbumArtUrl) @Html.ActionLink("Edit", "Edit", new { id=item.AlbumId }) |@Html.ActionLink("Details", "Details", new { id=item.AlbumId }) |@Html.ActionLink("Delete", "Delete", new { id=item.AlbumId })
数据库连接字符串配置
三步完成数据初始化
1. 实现模型类.
2. 在控制器中用脚手架视图.3. 选择数据初始化策略。Using Database Initializers使用数据库初始化
修改global.asax.cs文件
protected void Application_Start(){Database.SetInitializer(new MusicStoreDbInitializer());AreaRegistration.RegisterAllAreas();RegisterGlobalFilters(GlobalFilters.Filters);RegisterRoutes(RouteTable.Routes);}
Seeding a Database插入初始数据
public class MusicStoreDbInitializer: DropCreateDatabaseAlways{protected override void Seed(MusicStoreDB context){context.Artists.Add(new Artist {Name = "Al Di Meola"});context.Genres.Add(new Genre { Name = "Jazz" });context.Albums.Add(new Album{Artist = new Artist { Name="Rush" },Genre = new Genre { Name="Rock" },Price = 9.99m,Title = "Caravan"});base.Seed(context);}}
建立一个资源编辑Album
//// GET: /StoreManager/Edit/8public ActionResult Edit(int id = 0){Album album = db.Albums.Find(id);if (album == null){return HttpNotFound();}ViewBag.GenreId = new SelectList(db.Genres, "GenreId", "Name", album.GenreId);ViewBag.ArtistId = new SelectList(db.Artists, "ArtistId", "Name", album.ArtistId);return View(album);}
视图页面代码
@Html.DropDownList("GenreId", String.Empty)@Html.ValidationMessageFor(model => model.GenreId)
模型与视图模型
视图页面中可能需要来自多个Model的信息,因此引入视图Model对页面中需要显示的信息汇总到一个模型中。
public class AlbumEditViewModel{public Album AlbumToEdit { get; set; }public SelectList Genres { get; set; }public SelectList Artists { get; set; }}
The Edit View编辑视图
@using (Html.BeginForm()) {@Html.DropDownList("GenreId", String.Empty)@Html.EditorFor(model => model.Title)@Html.EditorFor(model => model.Price)}
解析后的html代码
Responding to the Edit POST Request 用POST选择器属性,执行相应的动作
//// POST: /StoreManager/Edit/8[HttpPost]public ActionResult Edit(Album album){if (ModelState.IsValid){db.Entry(album).State = EntityState.Modified;db.SaveChanges();return RedirectToAction("Index");}ViewBag.GenreId = new SelectList(db.Genres, "GenreId","Name", album.GenreId);ViewBag.ArtistId = new SelectList(db.Artists, "ArtistId","Name", album.ArtistId);return View(album);}
MODEL BINDING模型绑定
只更新Model中的部分值使用模型绑定的方式
[HttpPost]public ActionResult Edit(){var album = new Album();album.Title = Request.Form["Title"];album.Price = Decimal.Parse(Request.Form["Price"]);// ... and so on ...}
Explicit Model Binding显示模型绑定
将页面传入的模型保存在UPdateModel中,出现异常直接返回页面已经选择的值。
[HttpPost]public ActionResult Edit(){var album = new Album();try{UpdateModel(album);db.Entry(album).State = EntityState.Modified;db.SaveChanges();return RedirectToAction("Index");}catch{ViewBag.GenreId = new SelectList(db.Genres, "GenreId","Name", album.GenreId);ViewBag.ArtistId = new SelectList(db.Artists, "ArtistId","Name", album.ArtistId);return View(album);}}
TryUpdateModel也调用模型绑定,但是不会抛出异常。TryUpdateModel并返回一个布尔- true值如果模型绑定成功,该模型是有效的,返回真,无效返回false。
[HttpPost]public ActionResult Edit(){var album = new Album();if (TryUpdateModel(album)){db.Entry(album).State = EntityState.Modified;db.SaveChanges();return RedirectToAction("Index");}else{ViewBag.GenreId = new SelectList(db.Genres, "GenreId","Name", album.GenreId);ViewBag.ArtistId = new SelectList(db.Artists, "ArtistId","Name", album.ArtistId);return View(album);}}
验证模型绑定是否成功
[HttpPost]public ActionResult Edit(){var album = new Album();TryUpdateModel(album);if (ModelState.IsValid){db.Entry(album).State = EntityState.Modified;db.SaveChanges();return RedirectToAction("Index");}else{ViewBag.GenreId = new SelectList(db.Genres, "GenreId","Name", album.GenreId);ViewBag.ArtistId = new SelectList(db.Artists, "ArtistId","Name", album.ArtistId);return View(album);}}