MVC 框架 - 高级示例


在第一章中,我们学习了 MVC 中控制器和视图如何交互。在本教程中,我们将向前迈出一步,学习如何使用模型并创建一个高级应用程序来创建、编辑、删除。并查看我们应用程序中的用户列表。

创建高级 MVC 应用程序

步骤 1 - 选择文件 → 新建 → 项目 → ASP.NET MVC Web 应用程序。将其命名为 AdvancedMVCApplication。单击“确定”。在下一个窗口中,选择“模板”作为“Internet 应用程序”,选择“查看引擎”作为“Razor”。请注意,我们这次使用的是模板而不是空应用程序。

MVC新互联网项目

这将创建一个新的解决方案项目,如以下屏幕截图所示。由于我们使用默认的 ASP.NET 主题,因此它附带了示例视图、控制器、模型和其他文件。

MVC 模型视图控制器

步骤 2 - 构建解决方案并运行应用程序以查看其默认输出,如以下屏幕截图所示。

MVC 示例 Internet 应用程序

步骤 3 - 添加一个新模型来定义用户数据的结构。右键单击“模型”文件夹,然后单击“添加”→“类”。将其命名为 UserModel 并单击“添加”。

MVC 添加模型步骤 1

MVC 添加模型步骤 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 - 右键单击​​模型,然后单击添加 → 类。将其命名为“用户”。这将在模型中创建 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 - 右键单击​​“视图”文件夹,然后单击“添加”→“视图”。

mvc_advanced_add_view

步骤 7 - 在下一个窗口中,选择视图名称为 UserAdd,将视图引擎选择为 Razor,然后选择创建强类型视图复选框。

MVC 高级用户添加视图

步骤 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高级应用1

与 UserAdd 类似,现在我们将使用给定的代码添加下面给出的另外四个视图 -

索引.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高级应用2

详情.cshtml

当我们点击用户记录时,该View将显示特定用户的详细信息。

@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 高级应用详细信息

编辑.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 高级应用详细信息

删除.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高级应用详细信息删除

步骤 9 - 我们已经在应用程序中添加了模型和视图。现在最后我们将为我们的视图添加一个控制器。右键单击 Controllers 文件夹,然后单击添加 → 控制器。将其命名为 UserController。

MVC 高级添加控制器

默认情况下,您的控制器类将使用以下代码创建 -

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 - 右键单击​​索引方法并选择创建视图为我们的索引页面创建一个视图(它将列出所有用户并提供创建新用户的选项)。

MVC高级添加索引视图

步骤 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 文件并将默认控制器更改为用户。

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

这就是我们启动并运行高级应用程序所需的全部内容。

步骤 13 - 现在运行应用程序。您将能够看到一个应用程序,如以下屏幕截图所示。您可以执行添加、查看、编辑和删除用户的所有功能,如我们在前面的屏幕截图中看到的那样。

MVC 高级添加索引最终