[翻译:ASP.NET MVC 教程]用ASP.NET MVC 创建一个电影数据库应用程序——补充
对于该教程而言,缺少了删除已存在的电影记录的功能。因此,我在这里给出删除功能的代码供大家参考学习。
另外,需要注意的是要为VS2008打上SP1服务包,不然就不能使用ADO.NET Entity Data Model功能了。
附按本教程制作的MovieDatabase源代码(点击下载)
一、在Controllers\HomeController.cs文件中添加下列代码:
//
// GET: /Home/Delete/5
public ActionResult Delete(int id)
{
var contactToDelete = (from c in _db.MovieSet
where c.Id == id
select c).FirstOrDefault();
return View(contactToDelete);
}
//
// POST: /Home/Delete/5
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Delete(Movie contactToDelete)
{
try
{
var originalContact = (from c in _db.MovieSet
where c.Id == contactToDelete.Id
select c).FirstOrDefault();
_db.DeleteObject(originalContact);
_db.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
二、按下述添加删除视图:
1.在Controllers\HomeController.cs文件Delete区段中,右击并选择菜单选项Add View…(如下图所示)
2.将该视图命名为Delete(如下图所示)
3.在Views\Home\Delete.aspx文件中添加如下代码:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MovieDatabase.Models.Movie>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Delete
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Delete</h2>
<p>
Are you sure that you want to delete the Movie
<%= Model.Title %> for its Director <%=Model.Director %>?
</p>
<% using (Html.BeginForm(new { Id = Model.Id }))
{ %>
<p>
<input type="submit" value="Delete" />
</p>
<% } %>
<div>
<%=Html.ActionLink("Back to List", "Index") %>
</div>
</asp:Content>
三、编译运行