文章出處
后臺代碼
添加頁面
主頁面(列表頁面)
修改頁面
文章列表
就當是記筆記吧,這里,就不講什么版式了,首先上數據庫腳本,這個是我這次練習用到的數據庫腳本:
USE [DB_USERS] GO /****** Object: Table [dbo].[Student] Script Date: 10/31/2015 16:44:06 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE [dbo].[Student]( [s_ID] [INT] IDENTITY(1,1) NOT NULL, [s_Name] [NVARCHAR](10) NULL, [s_Sex] [CHAR](2) NULL, [s_Age] [INT] NULL, [c_ID] [INT] NOT NULL, CONSTRAINT [PK__Studnet__2F3DA3BC267ABA7A] PRIMARY KEY CLUSTERED ( [s_ID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO SET ANSI_PADDING OFF GO ALTER TABLE [dbo].[Student] WITH CHECK ADD FOREIGN KEY([c_ID]) REFERENCES [dbo].[Classes] ([c_ID]) GO
USE [DB_USERS] GO /****** Object: Table [dbo].[Classes] Script Date: 10/31/2015 16:44:51 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[Classes]( [c_ID] [INT] NOT NULL, [c_Name] [NVARCHAR](50) NULL, PRIMARY KEY CLUSTERED ( [c_ID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO
下面就是后臺的代碼了:

1 using MVCFirstApp.Models; 2 using System; 3 using System.Collections.Generic; 4 using System.Data; 5 using System.Data.Entity.Infrastructure; 6 using System.Linq; 7 using System.Web; 8 using System.Web.Mvc; 9 10 namespace MVCFirstApp.Controllers 11 { 12 public class StudentController : Controller 13 { 14 15 public StudentController() 16 17 { 18 //關閉實體驗證 19 db.Configuration.ValidateOnSaveEnabled = false; 20 } 21 DB_USERSEntities db = new DB_USERSEntities(); 22 // 23 // GET: /Student/ 24 25 public ActionResult Index() 26 { 27 28 List<Student> list = db.Student.Include("Classes").ToList(); 29 30 return View(list); //將list對象傳給視圖里的Model屬性 31 } 32 33 /// <summary> 34 /// 35 /// </summary> 36 /// <returns></returns> 37 //public ActionResult Delete(int id) //這里的id要和路由里面的id參數一樣,不區分大小寫 38 //{ 39 40 // Student stu = new Student() { s_ID = id }; 41 42 // #region 刪除的方法之一 43 // //刪除的方法之一 44 // //加入到數據上下文中 45 // //使用Remove方法刪除。必須先Attach 46 47 // //db.Student.Attach(stu); 48 // //db.Student.Remove(stu); 49 50 51 // //db.SaveChanges(); //保存到數據庫 52 // #endregion 53 54 // #region 刪除的方法之二 55 // //用過上下文對象的Entity方法,來把對象加入到EF中 56 // DbEntityEntry entry = db.Entry<Student>(stu); 57 58 // entry.State = EntityState.Deleted; 59 // db.SaveChanges();//保存到數據庫 60 61 // #endregion 62 63 // // return Redirect("/Student/Index"); 64 65 // return RedirectToAction("index"); //刪除的時候,調用重定向方法,有一個缺點,就是不知道是刪除成功還是失敗 66 67 // //刪除的時候,我們還可以使用js代碼,向用戶返回刪除成功還是失敗 68 // //Response.Write("<script></script>"); 69 70 //} 71 72 73 /// <summary> 74 /// 刪除 75 /// </summary> 76 /// <param name="id"></param> 77 public void Delete(int id) //這里的id參數必須要和路由里面的id參數一樣,才可以,將參數id傳到控制器方法,不過不區分大小寫,即寫ID也行 78 { 79 80 Student stu = new Student() { s_ID = id }; 81 82 #region 刪除的方法之一 83 //刪除的方法之一 84 //加入到數據上下文中 85 //使用Remove方法刪除。必須先Attach 86 87 //db.Student.Attach(stu); 88 //db.Student.Remove(stu); 89 90 91 //db.SaveChanges(); //保存到數據庫 92 #endregion 93 94 #region 刪除的方法之二 95 //用過上下文對象的Entity方法,來把對象加入到EF中 96 DbEntityEntry entry = db.Entry<Student>(stu); 97 98 entry.State = EntityState.Deleted; 99 db.SaveChanges();//保存到數據庫 100 101 #endregion 102 103 // return Redirect("/Student/Index"); 104 105 // return RedirectToAction("index"); //刪除的時候,調用重定向方法,有一個缺點,就是不知道是刪除成功還是失敗 106 107 //刪除的時候,我們還可以使用js代碼,向用戶返回刪除成功還是失敗 108 //window.location.href重新定向到新地址,不打開新窗口 109 Response.Write("<script>alert('刪除成功~~~');window.location.href='/Student/Index';</script>"); 110 111 } 112 113 /// <summary> 114 /// 修改 115 /// </summary> 116 /// <param name="id"></param> 117 /// <returns></returns> 118 public ActionResult Modify(int id) 119 { 120 //根據ID查詢Student表中的數據 121 Student stu = (from s in db.Student where s.s_ID == id select s).FirstOrDefault(); 122 123 124 //原始的方式,做下拉框 125 //查詢班級集合數據,并做成下拉框 126 //List<Classes> listClass = db.Classes.ToList(); 127 //ViewBag.ListClassData = listClass; 128 129 130 //LINQ to Entities 不識別方法“System.String ToString()” 131 //List<SelectListItem> listClass = (from c in db.Classes 132 // select new SelectListItem() { Text = c.c_Name, Value = c.c_ID.ToString(), Selected = (stu.c_ID==c.c_ID) }).ToList(); 133 134 var listClass = db.Classes.ToList().Select(c => new SelectListItem() { Text = c.c_Name, Value = c.c_ID.ToString(), Selected = (stu.c_ID == c.c_ID) }); 135 136 //這里就有個疑問了,我們已經傳了Student到View方法中,班級的數據該怎么傳遞到后臺頁面? 137 138 //PS:控制器上的Action方法,向視圖傳遞數據,除了通過View()方法,將數據傳遞到視圖中的Model屬性之外, 139 //還有三種方式,Viewbag,ViewData,Tempdata 140 141 ViewBag.ListClassData = listClass; 142 143 return View(stu); //加載視圖,并傳遞要修改的數據 144 } 145 146 [HttpPost] 147 public ActionResult Modify(Student model) 148 { 149 //將要修改的值,放到數據上下文中 150 DbEntityEntry entry= db.Entry<Student>(model); 151 entry.State = EntityState.Unchanged; 152 entry.Property("s_Name").IsModified = true; 153 entry.Property("c_ID").IsModified = true; 154 db.SaveChanges(); //將修改之后的值保存到數據庫中 155 return Redirect("Index"); 156 } 157 158 /// <summary> 159 /// 添加 160 /// </summary> 161 /// <returns></returns> 162 public ActionResult Add() 163 { 164 var listClass = db.Classes.ToList().Select(c => new SelectListItem() {Text=c.c_Name,Value=c.c_ID.ToString(),Selected=true }); 165 166 ViewBag.ListClass = listClass; 167 return View(); 168 } 169 170 [HttpPost] 171 public ActionResult Add(Student entity) 172 { 173 DbEntityEntry entry= db.Entry<Student>(entity); 174 entry.State = EntityState.Added; 175 db.SaveChanges(); 176 return RedirectToAction("index"); 177 } 178 } 179 }
然后就是頁面的代碼了:

@model MVCFirstApp.Models.Student @{ Layout = null; } @using MVCFirstApp.Models; <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Add</title> </head> <body> <form action="~/Student/Add" method="post"> <input type="submit" value="添加" /> <table> <tr> <td>姓名:</td> <td>@Html.EditorFor(model=>model.s_Name)</td> </tr> <tr> <td>性別:</td> <td>男:@Html.RadioButtonFor(model=>model.s_Sex,"男")女:@Html.RadioButtonFor(model=>model.s_Sex,"女")</td> </tr> <tr> <td>年齡:</td> <td>@Html.EditorFor(model => model.s_Age)</td> </tr> <tr> <td>班級:</td> <td>@Html.DropDownList("C_ID", @ViewBag.ListClass as IEnumerable<SelectListItem>)</td> </tr> </table> </form> </body> </html>

@{ Layout = null; } @using MVCFirstApp.Models; <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> <link href="~/Scripts/My.css" rel="stylesheet" /> </head> <body> <table class="mytable"> <tr> <th>學號</th> <th>姓名</th> <th>性別</th> <th>年齡</th> <th>班級名</th> <th>操作</th> </tr> <!--視圖里面包含一個Model屬性,可以通過Action方法中的View方法來賦值--> @foreach (Student stu in Model) { <tr> <td>@stu.s_ID</td> <td>@stu.s_Name</td> <td>@stu.s_Sex</td> <td>@stu.s_Age</td> <td>@stu.Classes.c_Name</td> <!--傳參數--> <td>@Html.ActionLink("修改", "Modify", new { id=@stu.s_ID})@Html.ActionLink("刪除", "Delete", new { id=@stu.s_ID})@Html.ActionLink("增加", "Add")</td> </tr> } </table> </body> </html>

@model MVCFirstApp.Models.Student @*指定了model類型的視圖就叫強類型視圖, 好處:VS可以推斷出model的類型,從而提供提示,model本來是動態的類型,使用的時候,一般都要轉類型,使用as來轉*@ @{ Layout = null; } @using MVCFirstApp.Models; <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Modify</title> </head> <body> <form method="post" action="/Student/Modify"> @*添加一個隱藏域*@ @*不添加隱藏域,點擊修改的時候,ID的屬性傳不到Action方法*@ @*修改,必須要傳主鍵過去,SID必須傳,所以隱藏域不能少*@ <input type="hidden" name="s_ID" value="@Model.s_ID"><table> <tr> <td>姓名:</td> @*name屬性的值,要和value里面綁定的屬性名字一樣,這樣在修改的時候,才可以把參數傳遞到Action方法*@ <td><input type="text" name="s_Name" value="@Model.s_Name" /></td> @*文本框的name屬性也使用和Model.s_Name一樣,模型綁定*@ <td>班級:</td> @*班級要生成下拉框,要有班級數據*@ <td> @*dropDownlist第一個參數的字段,必須要和數據庫中的字段一樣,這里是將班級名稱列出來,*@ @Html.DropDownList("c_ID", ViewBag.ListClassData as IEnumerable<SelectListItem>) @*ViewBag是動態的類型,使用的時候,需要轉一下類型*@ @*下面這個是生成下拉框最原始的方式,有個不方便,就是要選中默認值*@ @*<select name="c_ID"> @foreach (Classes c in @ViewBag.ListClassData as List<Classes>) { //如果集合中的班級號,和Model里面的班級號相等,就在option標簽,加上Selected if (c.c_ID == Model.c_ID) { <option value="@c.c_ID" selected>@c.c_Name</option> } else { <option value="@c.c_ID">@c.c_Name</option> } } </select>*@ </td> <td>性別:</td> @*name屬性的值,要和value里面綁定的屬性名字一樣,這樣在修改的時候,才可以把參數傳遞到Action Post方式的方法*@ <td><input type="text" name="s_Sex" value="@Model.s_Sex" /></td> <td>年齡:</td> <td><input type="text" name="s_Age" value="@Model.s_Age" /></td> <td><input type="submit" value="確定" /></td> </tr> </table> </form> </body> </html>
好了,就這么多了。
文章列表
全站熱搜