在第一個MVC教學章中,我們學會了如何在MVC控制器和檢視進行互動。在本教學中,我們將向前更進一步,學習如何使用模型建立高階應用程式來建立,編輯,刪除使用者,在我們的應用程式中檢視列表。
第1步:選擇 File->New->Project->ASP.NET MVC Web應用. 並命名為:AdvancedMVCApplication. 單擊確定。在接下來的視窗中,選擇模板作為網際網路應用程式和檢視引擎為Razor。注意,我們這個時候使用的是模板,而不是一個空的應用程式。
這將建立一個新的解決方案的專案,如下圖所示。由於我們使用的是預設的ASP.NET主題,它帶有樣本檢視,控制器,模型和其他檔案。
構建解決方案,並執行應用程式,看看它的預設輸出,如下:
第2步:我們將增加一個新的模式,將定義的使用者資料結構。右鍵單擊Models檔案夾,然後點選 Add->Class. 命名為UserModel,然後單擊Add。
第3步:現在將以下程式碼複製到新建立的UserModel.cs:
using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Web.Mvc.Html; namespace AdvancedMVCApplication.Models { public class UserModels { [Required] public int Id { get; set; } [DisplayName("First Name")] [Required(ErrorMessage = "First name is required")] public string FirstName { get; set; } [Required] public string LastName { get; set; } public string Address { get; set; } [Required] [StringLength(50)] public string Email { get; set; } [DataType(DataType.Date)] public DateTime DOB { get; set; } [Range(100,1000000)] public decimal Salary { get; set; } } }
在上面的程式碼中,我們指定的使用者模型驗證所有的引數,其資料型別和如所需的欄位和長度。
第4步:現在,我們有使用者模型準備儲存資料,現在建立一個類檔案Users.cs 其中將包含用於檢視使用者,新增,編輯和刪除使用者的方法。右鍵單擊模型,然後單擊 Add->Class. 命名為:Users. 這將建立users.cs類在Models內部。
複製下面的程式碼到users.cs類。
using System; using System.Collections.Generic; using System.EnterpriseServices; namespace AdvancedMVCApplication.Models { public class Users { public ListUserList = new List (); //action to get user details public UserModels GetUser(int id) { UserModels usrMdl = null; foreach (UserModels um in UserList) if (um.Id == id) usrMdl = um; return usrMdl; } //action to create new user public void CreateUser(UserModels userModel) { UserList.Add(userModel); } //action to udpate existing user public void UpdateUser(UserModels userModel) { foreach (UserModels usrlst in UserList) { if (usrlst.Id == userModel.Id) { usrlst.Address = userModel.Address; usrlst.DOB = userModel.DOB; usrlst.Email = userModel.Email; usrlst.FirstName = userModel.FirstName; usrlst.LastName = userModel.LastName; usrlst.Salary = userModel.Salary; break; } } } //action to delete exising user public void DeleteUser(UserModels userModel) { foreach (UserModels usrlst in UserList) { if (usrlst.Id == userModel.Id) { UserList.Remove(usrlst); break; } } } } }
第5步:一旦我們有UserModel.cs和Users.cs,將增加瀏覽模型檢視,新增,編輯和刪除使用者。首先,讓我們建立一個檢視用來建立使用者。右鍵單擊Views檔案夾,然後點選 Add->View.
在接下來的視窗中,選擇檢視名稱為UserAdd,檢視引擎為Razor,並選擇建立一個強型別的檢視核取方塊。
單擊新增。在預設情況下這將建立下列CSHML程式碼,如下所示:
@model AdvancedMVCApplication.Models.UserModels @{ ViewBag.Title = "UserAdd"; } <h2>UserAdd</h2> @using (Html.BeginForm()) { @Html.ValidationSummary(true) <fieldset> <legend>UserModels</legend> <div class="editor-label"> @Html.LabelFor(model => model.FirstName) </div> <div class="editor-field"> @Html.EditorFor(model => model.FirstName) @Html.ValidationMessageFor(model => model.FirstName) </div> <div class="editor-label"> @Html.LabelFor(model => model.LastName) </div> <div class="editor-field"> @Html.EditorFor(model => model.LastName) @Html.ValidationMessageFor(model => model.LastName) </div> <div class="editor-label"> @Html.LabelFor(model => model.Address) </div> <div class="editor-field"> @Html.EditorFor(model => model.Address) @Html.ValidationMessageFor(model => model.Address) </div> <div class="editor-label"> @Html.LabelFor(model => model.Email) </div> <div class="editor-field"> @Html.EditorFor(model => model.Email) @Html.ValidationMessageFor(model => model.Email) </div> <div class="editor-label"> @Html.LabelFor(model => model.DOB) </div> <div class="editor-field"> @Html.EditorFor(model => model.DOB) @Html.ValidationMessageFor(model => model.DOB) </div> <div class="editor-label"> @Html.LabelFor(model => model.Salary) </div> <div class="editor-field"> @Html.EditorFor(model => model.Salary) @Html.ValidationMessageFor(model => model.Salary) </div> <p> <input type="submit" value="Create" /> </p> </fieldset> } <div> @Html.ActionLink("Back to List", "Index") </div> @section Scripts { @Scripts.Render("~/bundles/jqueryval") }
正如所看到的,這個檢視包含欄位的所有屬性資訊的驗證訊息,標籤等,此檢視在我們最終的應用程式看起來像這樣:
類似UserAdd,,現在我們將增加如下四個檢視程式碼:
該檢視將顯示所有存在於我們的系統中的使用者在Index頁面上。
@model IEnumerable<AdvancedMVCApplication.Models.UserModels> @{ ViewBag.Title = "Index"; } <h2>Index</h2> <p> @Html.ActionLink("Create New", "UserAdd") </p> <table> <tr> <th> @Html.DisplayNameFor(model => model.FirstName) </th> <th> @Html.DisplayNameFor(model => model.LastName) </th> <th> @Html.DisplayNameFor(model => model.Address) </th> <th> @Html.DisplayNameFor(model => model.Email) </th> <th> @Html.DisplayNameFor(model => model.DOB) </th> <th> @Html.DisplayNameFor(model => model.Salary) </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.FirstName) </td> <td> @Html.DisplayFor(modelItem => item.LastName) </td> <td> @Html.DisplayFor(modelItem => item.Address) </td> <td> @Html.DisplayFor(modelItem => item.Email) </td> <td> @Html.DisplayFor(modelItem => item.DOB) </td> <td> @Html.DisplayFor(modelItem => item.Salary) </td> <td> @Html.ActionLink("Edit", "Edit", new { id=item.Id }) | @Html.ActionLink("Details", "Details", new { id=item.Id }) | @Html.ActionLink("Delete", "Delete", new { id=item.Id }) </td> </tr> } </table>
此檢視在我們最終的應用程式看起來如下:
此檢視將顯示特定使用者的詳細資訊,當我們點選使用者記錄。
@model AdvancedMVCApplication.Models.UserModels @{ ViewBag.Title = "Details"; } <h2>Details</h2> <fieldset> <legend>UserModels</legend> <div class="display-label"> @Html.DisplayNameFor(model => model.FirstName) </div> <div class="display-field"> @Html.DisplayFor(model => model.FirstName) </div> <div class="display-label"> @Html.DisplayNameFor(model => model.LastName) </div> <div class="display-field"> @Html.DisplayFor(model => model.LastName) </div> <div class="display-label"> @Html.DisplayNameFor(model => model.Address) </div> <div class="display-field"> @Html.DisplayFor(model => model.Address) </div> <div class="display-label"> @Html.DisplayNameFor(model => model.Email) </div> <div class="display-field"> @Html.DisplayFor(model => model.Email) </div> <div class="display-label"> @Html.DisplayNameFor(model => model.DOB) </div> <div class="display-field"> @Html.DisplayFor(model => model.DOB) </div> <div class="display-label"> @Html.DisplayNameFor(model => model.Salary) </div> <div class="display-field"> @Html.DisplayFor(model => model.Salary) </div> </fieldset> <p> @Html.ActionLink("Edit", "Edit", new { id=Model.Id }) | @Html.ActionLink("Back to List", "Index") </p>
此檢視在我們最終的應用程式看起來像這樣:
這檢視將顯示現有使用者的詳細資訊的編輯表單。
@model AdvancedMVCApplication.Models.UserModels @{ ViewBag.Title = "Edit"; } <h2>Edit</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) <fieldset> <legend>UserModels</legend> @Html.HiddenFor(model => model.Id) <div class="editor-label"> @Html.LabelFor(model => model.FirstName) </div> <div class="editor-field"> @Html.EditorFor(model => model.FirstName) @Html.ValidationMessageFor(model => model.FirstName) </div> <div class="editor-label"> @Html.LabelFor(model => model.LastName) </div> <div class="editor-field"> @Html.EditorFor(model => model.LastName) @Html.ValidationMessageFor(model => model.LastName) </div> <div class="editor-label"> @Html.LabelFor(model => model.Address) </div> <div class="editor-field"> @Html.EditorFor(model => model.Address) @Html.ValidationMessageFor(model => model.Address) </div> <div class="editor-label"> @Html.LabelFor(model => model.Email) </div> <div class="editor-field"> @Html.EditorFor(model => model.Email) @Html.ValidationMessageFor(model => model.Email) </div> <div class="editor-label"> @Html.LabelFor(model => model.DOB) </div> <div class="editor-field"> @Html.EditorFor(model => model.DOB) @Html.ValidationMessageFor(model => model.DOB) </div> <div class="editor-label"> @Html.LabelFor(model => model.Salary) </div> <div class="editor-field"> @Html.EditorFor(model => model.Salary) @Html.ValidationMessageFor(model => model.Salary) </div> <p> <input type="submit" value="Save" /> </p> </fieldset> } <div> @Html.ActionLink("Back to List", "Index") </div> @section Scripts { @Scripts.Render("~/bundles/jqueryval") }
此檢視在我們的應用程式看起來如下:
此檢視將顯示表單用於刪除現有使用者。
@model AdvancedMVCApplication.Models.UserModels @{ ViewBag.Title = "Delete"; } <h2>Delete</h2> <h3>Are you sure you want to delete this?</h3> <fieldset> <legend>UserModels</legend> <div class="display-label"> @Html.DisplayNameFor(model => model.FirstName) </div> <div class="display-field"> @Html.DisplayFor(model => model.FirstName) </div> <div class="display-label"> @Html.DisplayNameFor(model => model.LastName) </div> <div class="display-field"> @Html.DisplayFor(model => model.LastName) </div> <div class="display-label"> @Html.DisplayNameFor(model => model.Address) </div> <div class="display-field"> @Html.DisplayFor(model => model.Address) </div> <div class="display-label"> @Html.DisplayNameFor(model => model.Email) </div> <div class="display-field"> @Html.DisplayFor(model => model.Email) </div> <div class="display-label"> @Html.DisplayNameFor(model => model.DOB) </div> <div class="display-field"> @Html.DisplayFor(model => model.DOB) </div> <div class="display-label"> @Html.DisplayNameFor(model => model.Salary) </div> <div class="display-field"> @Html.DisplayFor(model => model.Salary) </div> </fieldset> @using (Html.BeginForm()) { @Html.AntiForgeryToken() <p> <input type="submit" value="Delete" /> | @Html.ActionLink("Back to List", "Index") </p> }
此檢視在我們最終的應用程式看起來像這樣:
第6步:我們已經增加模型和檢視在應用程式中。現在新增一個控制器,用於檢視。 右鍵單擊Controllers檔案夾,然後點選 Add->Controller. 命名為: UserController.
預設情況下,控制器類將用下面的程式碼來建立:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using AdvancedMVCApplication.Models; namespace AdvancedMVCApplication.Controllers { public class UserController : Controller { private static Users _users = new Users(); public ActionResult Index() { return View(_users.UserList); } } }
在上面的程式碼中,Index方法將在呈現使用者列表在Index頁面上。
第6步:右鍵單擊Index方法,並選擇建立檢視來建立Index頁面檢視(其中會列出所有使用者,並提供選項來建立新的使用者)。
第7步:現在新增以下程式碼UserController.cs。在這段程式碼中,我們建立操作方法針對不同的使用者操作,返回之前建立相應的檢視。
我們將新增兩個方法為每個操作:GET和POST。當獲取資料時,其HttpGet被使用。HttpPost將用於建立/更新資料。例如,當我們要新增新使用者,需要一個表單來新增使用者,這是一個GET操作。當我們填寫表格,並提交這些值,需要使用POST方法。
//Action for Index View public ActionResult Index() { return View(_users.UserList); } //Action for UserAdd View [HttpGet] public ActionResult UserAdd() { return View(); } [HttpPost] public ActionResult UserAdd(UserModels userModel) { _users.CreateUser(userModel); return View("Index", _users.UserList); } //Action for Details View [HttpGet] public ActionResult Details(int id) { return View(_users.UserList.FirstOrDefault(x => x.Id == id)); } [HttpPost] public ActionResult Details() { return View("Index", _users.UserList); } //Action for Edit View [HttpGet] public ActionResult Edit(int id) { return View(_users.UserList.FirstOrDefault(x=>x.Id==id)); } [HttpPost] public ActionResult Edit(UserModels userModel) { _users.UpdateUser(userModel); return View("Index", _users.UserList); } //Action for Delete View [HttpGet] public ActionResult Delete(int id) { return View(_users.UserList.FirstOrDefault(x => x.Id == id)); } [HttpPost] public ActionResult Delete(UserModels userModel) { _users.DeleteUser(userModel); return View("Index", _users.UserList); } sers.UserList); }
第8步:最後要做的就是到App_Start檔案夾找到RouteConfig.cs檔案,並更改預設的控制器。
defaults: new { controller = "User", action = "Index", id = UrlParameter.Optional }
第9步:下面是高階應用範例程式啟動和執行。現在執行應用程式。將能夠看到這樣的應用程式,並可以執行新增,檢視,編輯,刪除使用者,因為在前面的截圖已經看到了所有功能。