MVC 框架 - 高階示例



在第一章中,我們學習了控制器和檢視在 MVC 中如何互動。在本教程中,我們將更進一步,學習如何使用模型並建立一個高階應用程式來建立、編輯、刪除和檢視應用程式中使用者的列表。

建立高階 MVC 應用程式

步驟 1 - 選擇檔案 → 新建 → 專案 → ASP.NET MVC Web 應用程式。將其命名為 AdvancedMVCApplication。單擊確定。在下一個視窗中,選擇模板為 Internet 應用程式,檢視引擎為 Razor。注意,這次我們使用的是模板,而不是空應用程式。

MVC New Internet Project

這將建立一個新的解決方案專案,如下面的螢幕截圖所示。由於我們使用的是預設的 ASP.NET 主題,因此它包含示例檢視、控制器、模型和其他檔案。

MVC Model View Controller

步驟 2 - 構建解決方案並執行應用程式以檢視其預設輸出,如下面的螢幕截圖所示。

MVC Sample Internet Application

步驟 3 - 新增一個新的模型,它將定義使用者資料的結構。右鍵單擊 Models 資料夾,然後單擊新增 → 類。將其命名為 UserModel 並單擊新增。

MVC Add Model Step 1

MVC Add Model Step 2

步驟 4 - 將以下程式碼複製到新建立的 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; } 
   } 
} 

在上面的程式碼中,我們指定了使用者模型的所有引數、它們的資料型別以及驗證,例如必填欄位和長度。

現在我們已經準備好使用者模型來儲存資料,我們將建立一個類檔案 Users.cs,其中將包含檢視使用者、新增、編輯和刪除使用者的方法。

步驟 5 - 右鍵單擊 Models 並單擊新增 → 類。將其命名為 Users。這將在 Models 中建立 users.cs 類。將以下程式碼複製到 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; 
            } 
         } 
      } 
   } 
} 

一旦我們有了 UserModel.cs 和 Users.cs,我們將為我們的模型新增檢視,用於檢視使用者、新增、編輯和刪除使用者。首先讓我們建立一個檢視來建立一個使用者。

步驟 6 - 右鍵單擊 Views 資料夾,然後單擊新增 → 檢視。

mvc_advanced_add_view

步驟 7 - 在下一個視窗中,選擇檢視名稱為 UserAdd,檢視引擎為 Razor,並選中“建立強型別檢視”複選框。

MVC Advanced User Add View

步驟 8 - 單擊新增。這將預設建立以下 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") 
}

如您所見,此檢視包含所有欄位屬性的檢視詳細資訊,包括它們的驗證訊息、標籤等。此檢視在我們的最終應用程式中將如下所示。

MVC Advanced Application 1

與 UserAdd 類似,現在我們將新增下面給出的另外四個檢視及其程式碼:

Index.cshtml

此檢視將在索引頁面上顯示系統中存在的所有使用者。

@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>

此檢視在我們的最終應用程式中將如下所示。

MVC Advanced Application 2

Details.cshtml

當我們單擊使用者記錄時,此檢視將顯示特定使用者的詳細資訊。

@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>

此檢視在我們的最終應用程式中將如下所示。

MVC Advanced Application Details

Edit.cshtml

此檢視將顯示用於編輯現有使用者詳細資訊的編輯表單。

@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") 
}

此檢視在我們的應用程式中將如下所示。

MVC Advanced Application Details

Delete.cshtml

此檢視將顯示用於刪除現有使用者的表單。

@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> 
}

此檢視在我們的最終應用程式中將如下所示。

MVC advanced Application Details Delete

步驟 9 - 我們已經在應用程式中添加了模型和檢視。現在,我們最終將為我們的檢視新增一個控制器。右鍵單擊 Controllers 資料夾,然後單擊新增 → 控制器。將其命名為 UserController。

MVC Advanced Add Controller

預設情況下,您的控制器類將使用以下程式碼建立:

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 方法將在渲染索引頁面上的使用者列表時使用。

步驟 10 - 右鍵單擊 Index 方法並選擇建立檢視,為我們的索引頁面建立檢視(它將列出所有使用者並提供建立新使用者的選項)。

MVC Advanced add Index View

步驟 11 - 現在在 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);

步驟 12 - 最後要做的是轉到 App_Start 資料夾中的 RouteConfig.cs 檔案並將預設控制器更改為 User。

defaults: new { controller = "User", action = "Index", id = UrlParameter.Optional } 

這就是使我們的高階應用程式執行所需的一切。

步驟 13 - 現在執行應用程式。您將能夠看到一個應用程式,如下面的螢幕截圖所示。您可以執行新增、檢視、編輯和刪除使用者的所有功能,就像我們在之前的螢幕截圖中看到的那樣。

MVC Advanced Add Index Final
廣告