MVC5学习笔记,其实就是敲了一遍官网代码,官网地址:http://www.asp.net/mvc
接着上一篇 MVC5学习系列——添加模型(Model)、链接字符串,这次我们来访问模型数据。
我们看一下列表页面Index.cshtml的代码:
@model IEnumerable
@{
Layout = null;
}
Index
@Html.ActionLink("Create New", "Create")
@Html.DisplayNameFor(model => model.Title)
@Html.DisplayNameFor(model => model.ReleaseDate)
@Html.DisplayNameFor(model => model.Genre)
@Html.DisplayNameFor(model => model.Price)
@foreach (var item in Model) {
@Html.DisplayFor(modelItem => item.Title)
@Html.DisplayFor(modelItem => item.ReleaseDate)
@Html.DisplayFor(modelItem => item.Genre)
@Html.DisplayFor(modelItem => item.Price)
@Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
@Html.ActionLink("Details", "Details", new { id=item.ID }) |
@Html.ActionLink("Delete", "Delete", new { id=item.ID })
}
开始是这样的:
我们再看一下添加电影页面Create.cshtml的代码:
@model DDZ.MVC5Test.Models.Movie
@{
Layout = null;
}
Create
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
Movie
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.ReleaseDate, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.ReleaseDate, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ReleaseDate, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Genre, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Genre, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Genre, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Price, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Price, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Price, "", new { @class = "text-danger" })
}
@Html.ActionLink("Back to List", "Index")
下面我们就添加一个电影试试:
我们在从VS中看看效果:
看上去很简单啊!
随便点点再试试,点击"Edit":
再看一下Edit.cshtml页面的代码:
@model DDZ.MVC5Test.Models.Movie
@{
Layout = null;
}
Edit
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
Movie
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.ID)
@Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.ReleaseDate, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.ReleaseDate, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ReleaseDate, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Genre, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Genre, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Genre, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Price, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Price, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Price, "", new { @class = "text-danger" })
}
@Html.ActionLink("Back to List", "Index")
修改一下,试试:
点击“Details”:
接着是Details.cshtml页面的代码:
@model DDZ.MVC5Test.Models.Movie
@{
Layout = null;
}
Details
Movie
-
@Html.DisplayNameFor(model => model.Title)
-
@Html.DisplayFor(model => model.Title)
-
@Html.DisplayNameFor(model => model.ReleaseDate)
-
@Html.DisplayFor(model => model.ReleaseDate)
-
@Html.DisplayNameFor(model => model.Genre)
-
@Html.DisplayFor(model => model.Genre)
-
@Html.DisplayNameFor(model => model.Price)
-
@Html.DisplayFor(model => model.Price)
@Html.ActionLink("Edit", "Edit", new { id = Model.ID }) |
@Html.ActionLink("Back to List", "Index")
下面我们试试删除:
再点击“Delete”就真的没有了。
最后是Delete.cshtml页面的代码:
@model DDZ.MVC5Test.Models.Movie
@{
Layout = null;
}
Delete
Are you sure you want to delete this?
Movie
-
@Html.DisplayNameFor(model => model.Title)
-
@Html.DisplayFor(model => model.Title)
-
@Html.DisplayNameFor(model => model.ReleaseDate)
-
@Html.DisplayFor(model => model.ReleaseDate)
-
@Html.DisplayNameFor(model => model.Genre)
-
@Html.DisplayFor(model => model.Genre)
-
@Html.DisplayNameFor(model => model.Price)
-
@Html.DisplayFor(model => model.Price)
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
|
@Html.ActionLink("Back to List", "Index")
}
到这里,添加、修改、删除都有了,就剩下查询了。这篇就写到这里了,不知道下篇有没有查询。谢谢!
2016-01-23更新
其实实体查询 除了代码自动生成的LINQ To Entities之外,还有Entity SQL和Native SQL。这里补充说一下在EF中使用后两种方式的添加修改删除。
首先对比一下添加的代码:
LINQ To Entities添加电影
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,Title,ReleaseDate,Genre,Price")] Movie movie)
{
if (ModelState.IsValid)
{
db.Movies.Add(movie);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(movie);
}
Native SQL添加电影
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,Title,ReleaseDate,Genre,Price")] Movie movie)
{
if (ModelState.IsValid)
{
var insertSql = @"insert into Movies(Title, ReleaseDate,Genre,Price)
values (@Title, @ReleaseDate,@Genre,@Price)";
var parameters = new System.Data.Common.DbParameter[]
{
new System.Data.SqlClient.SqlParameter { ParameterName = "Title", Value = movie.Title },
new System.Data.SqlClient.SqlParameter { ParameterName = "ReleaseDate", Value = movie.ReleaseDate },
new System.Data.SqlClient.SqlParameter { ParameterName = "Genre", Value = movie.Genre },
new System.Data.SqlClient.SqlParameter { ParameterName = "Price", Value = movie.Price }
};
try
{
var rowCount = db.Database.ExecuteSqlCommand(insertSql, parameters);
}
catch (Exception ex)
{
throw;
}
return RedirectToAction("Index");
}
return View(movie);
}
然后就是比较修改代码:
LINQ To Entities修改电影
// POST: Movies/Edit/5
// 为了防止“过多发布”攻击,请启用要绑定到的特定属性,有关
// 详细信息,请参阅 http://go.microsoft.com/fwlink/?LinkId=317598。
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "ID,Title,ReleaseDate,Genre,Price")] Movie movie)
{
if (ModelState.IsValid)
{
db.Entry(movie).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(movie);
}
Native SQL修改电影
// POST: Movies/Edit/5
// 为了防止“过多发布”攻击,请启用要绑定到的特定属性,有关
// 详细信息,请参阅 http://go.microsoft.com/fwlink/?LinkId=317598。
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "ID,Title,ReleaseDate,Genre,Price")] Movie movie)
{
if (ModelState.IsValid)
{
var updateSql = @"update Movies set Title=@Title,ReleaseDate=@ReleaseDate,Genre=@Genre,Price=@Price
where ID=@ID";
var parameters = new System.Data.Common.DbParameter[]
{
new System.Data.SqlClient.SqlParameter { ParameterName = "Title", Value = movie.Title },
new System.Data.SqlClient.SqlParameter { ParameterName = "ReleaseDate", Value = movie.ReleaseDate },
new System.Data.SqlClient.SqlParameter { ParameterName = "Genre", Value = movie.Genre },
new System.Data.SqlClient.SqlParameter { ParameterName = "Price", Value = movie.Price },
new System.Data.SqlClient.SqlParameter { ParameterName = "ID", Value = movie.ID }
};
try
{
var rowCount = db.Database.ExecuteSqlCommand(updateSql, parameters);
return RedirectToAction("Index");
}
catch (Exception ex)
{
throw;
}
}
return View(movie);
}
再就是比较删除代码:
LINQ To Entities删除电影
// POST: Movies/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Movie movie = db.Movies.Find(id);
db.Movies.Remove(movie);
db.SaveChanges();
return RedirectToAction("Index");
}
Native SQL 删除电影
// POST: Movies/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
var delSql = "delete from Movies where ID = @ID";
var parameters = new System.Data.Common.DbParameter[]
{
new System.Data.SqlClient.SqlParameter { ParameterName = "ID", Value = id }
};
try
{
var rowCount = db.Database.ExecuteSqlCommand(delSql, parameters);
}
catch (Exception ex)
{
throw;
}
return RedirectToAction("Index");
}
最后呢,对比一下查询代码:
LINQ To Entities查看电影详情
// GET: Movies/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Movie movie = db.Movies.Find(id);
if (movie == null)
{
return HttpNotFound();
}
return View(movie);
}
Native SQL 查看电影详情
// GET: Movies/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var selectSql = "select * from Movies where ID = @ID";
var parameters = new System.Data.Common.DbParameter[]
{
new System.Data.SqlClient.SqlParameter { ParameterName = "ID", Value = id }
};
var movie = db.Database.SqlQuery(selectSql, parameters).ToList().First();
if (movie == null)
{
return HttpNotFound();
}
return View(movie);
}
Entity SQL查看电影详情
// GET: Movies/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
//Querying with Object Services and Entity SQL
string selectSql = "select value t FROM Movies " +
"AS t WHERE t.id == @ID";
var objParameters = new System.Data.Entity.Core.Objects.ObjectParameter[]
{
new System.Data.Entity.Core.Objects.ObjectParameter("ID", id)
};
var movie = ((System.Data.Entity.Infrastructure.IObjectContextAdapter)db).ObjectContext.CreateQuery(selectSql, objParameters).ToList().First();
if (movie == null)
{
return HttpNotFound();
}
return View(movie);
}
最后呢,再说一下异步的事儿,执行SQL命令db.Database.ExecuteSqlCommand和保存db.SaveChanges都有其对应的异步方法,分别是:db.Database.ExecuteSqlCommandAsync()和db.SaveChangesAsync()。还有对应的查询的异步方法:db.Database.SqlQuery