MVC框架 - 高級示例
在第一個MVC教程章中,我們學會了如何在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 List
UserList = 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";
}
UserAdd
@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>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
正如所看到的,這個視圖包含字段的所有屬性信息的驗證消息,標籤等,此視圖在我們最終的應用程序看起來像這樣:
類似UserAdd,,現在我們將增加如下四個視圖代碼:
Index.cshtml
該視圖將顯示所有存在於我們的系統中的用戶在Index頁面上。
@model IEnumerable<AdvancedMVCApplication.Models.UserModels>
@{
ViewBag.Title = "Index";
}
Index
@Html.ActionLink("Create New", "UserAdd")
@Html.DisplayNameFor(model => model.FirstName) | @Html.DisplayNameFor(model => model.LastName) | @Html.DisplayNameFor(model => model.Address) | @Html.DisplayNameFor(model => model.Email) | @Html.DisplayNameFor(model => model.DOB) | @Html.DisplayNameFor(model => model.Salary) | |
---|---|---|---|---|---|---|
@Html.DisplayFor(modelItem => item.FirstName) | @Html.DisplayFor(modelItem => item.LastName) | @Html.DisplayFor(modelItem => item.Address) | @Html.DisplayFor(modelItem => item.Email) | @Html.DisplayFor(modelItem => item.DOB) | @Html.DisplayFor(modelItem => item.Salary) | @Html.ActionLink("Edit", "Edit", new { id=item.Id }) | @Html.ActionLink("Details", "Details", new { id=item.Id }) | @Html.ActionLink("Delete", "Delete", new { id=item.Id }) |
此視圖在我們最終的應用程序看起來如下:
Details.cshtml:
此視圖將顯示特定用戶的詳細信息,當我們點擊用戶記錄。
@model AdvancedMVCApplication.Models.UserModels
@{
ViewBag.Title = "Details";
}
Details
@Html.ActionLink("Edit", "Edit", new { id=Model.Id }) | @Html.ActionLink("Back to List", "Index")
此視圖在我們最終的應用程序看起來像這樣:
Edit.cshtml:
這視圖將顯示現有用戶的詳細信息的編輯表單。
@model AdvancedMVCApplication.Models.UserModels
@{
ViewBag.Title = "Edit";
}
Edit
@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>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
此視圖在我們的應用程序看起來如下:
Delete.cshtml:
此視圖將顯示窗體用於刪除現有用戶。
@model AdvancedMVCApplication.Models.UserModels
@{
ViewBag.Title = "Delete";
}
Delete
Are you sure you want to delete this?
@using (Html.BeginForm()) { @Html.AntiForgeryToken()| @Html.ActionLink("Back to List", "Index")
}此視圖在我們最終的應用程序看起來像這樣:
第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步:下面是高級應用示例程序啓動和運行。現在運行應用程序。將能夠看到這樣的應用程序,並可以執行添加,查看,編輯,刪除用戶,因爲在前面的截圖已經看到了所有功能。