一、web.cofnig数据库连接
二、初始化数据库及数据
using System.ComponentModel.DataAnnotations;
在Model类的Movie.cs里添加引用和下面的初始类
public class movieInitializer:DropCreateDatabaseIfModelChanges{ protected override void Seed(MovieDBContext context) { var movies=new List { new Movie{Title="when harry met sally", Price=4.6M}, new Movie{Title="Ghost", Price=200.0M}, }; movies.ForEach(d=>context.Movies.Add(d)); } }
然后在Global.asax.cs的protected void Application_Start()里添加如下代码:
Database.SetInitializer(new MovieInitializer());
三、添加MoviesControllers
Details注意ViewResult要改成:ActionReuslt因为我们要加个HttpNotFound而它是不能返回ViewResult对象的
public ActionResult Details(int id=0) { Movie movie = db.Movies.Find(id); if (movie == null) { return HttpNotFound(); } return View(movie); }
象Edit和Delte最好给一个初始值,以防提交的ID是空的
public ActionResult Edit(int id=2) { Movie movie = db.Movies.Find(id); if (movie == null) { return HttpNotFound(); } return View(movie); }
Mvc3改进了删除功能,加上了删除确认,目的是防止恶意代码没有经过确认就删除数据
当点击删除连接时只是返回确认信息:
public ActionResult Delete(int id) { Movie movie = db.Movies.Find(id); return View(movie); }
再点击确认按钮进行post提交删除
a)请注意查看View里的Delete.cshtml文件删除源文件:
@using (Html.BeginForm()) {| @Html.ActionLink("Back to List", "Index")
b)在生成html的确认删除源文件里可以看到自动生成了action="/movies/Delete/1:
下面是确认删除后执行的动作:
[HttpPost, ActionName("Delete")] public ActionResult DeleteConfirmed(int id=0) { Movie movie = db.Movies.Find(id); if (movie == null) { return HttpNotFound(); } db.Movies.Remove(movie); db.SaveChanges(); return RedirectToAction("Index"); }
四、内容搜索过滤功能
先来看SearchIndex.cshtml视图页:
@using (Html.BeginForm("SearchIndex", "Movies", FormMethod.Get)) {Genre:@Html.DropDownList("movieGenre","All")
Title:@Html.TextBox("SearchString")
}
下面是Controller:
public ActionResult SearchIndex(string movieGenre,string searchString) { var GenreLst = new List(); var GenreQry = from d in db.Movies orderby d.Genre select d.Genre; GenreLst.AddRange(GenreQry.Distinct()); ViewBag.movieGenre = new SelectList(GenreLst); var movies = from m in db.Movies select m; if (!String.IsNullOrEmpty(searchString)) { movies = movies.Where(s => s.Title.Contains(searchString)); } if (string.IsNullOrEmpty(movieGenre)) return View(movies); else { return View(movies.Where(x => x.Genre == movieGenre)); } }
下面是生成的html页面源代码:
五、Movie类和数据库连接上下文类MovieDBContext,注意引用using System.Data.Entity;
using System.Data.Entity; public class Movie { public int ID{ get;set;} public string Title{ get;set;} public decimal Price{ get;set;} } public class MovieDBContext:DbContext { public DbSetMovies{ get;set;} }
六、字段规则确认验证
public int ID { get; set; } [Required(ErrorMessage="标题必需要填写")] public string Title { get; set; } [Required(ErrorMessage="Price Required")] [Range(1,100,ErrorMessage="Price must be between $1 and $100")] [DisplayFormat(DataFormatString="{0:c}")] public decimal Price { get; set; }