ASP.NET MVC - 数据模型



本章将讨论在 ASP.NET MVC 框架应用程序中构建模型。一个模型存储根据控制器命令检索到的数据,并在视图中显示。

模型是一组类,您将在其中处理数据和业务逻辑。因此,模型基本上是特定于业务领域的容器。它用于与数据库交互。它还可以用于操作数据以实现业务逻辑。

让我们通过创建一个新的 ASP.Net MVC 项目来查看模型的一个简单示例。

步骤 1 - 打开 Visual Studio。单击“文件”→“新建”→“项目”菜单选项。

将打开一个新的项目对话框。

Open the Visual Studio

步骤 2 - 从左侧窗格中,选择“模板”→“Visual C#”→“Web”。

步骤 3 - 在中间窗格中,选择“ASP.NET Web 应用程序”。

步骤 4 - 在“名称”字段中输入项目名称“MVCSimpleApp”,然后单击“确定”继续。您将看到以下对话框,要求您设置 ASP.NET 项目的初始内容。

MVCSimpleApp

步骤 5 - 为简单起见,选择“空”选项,并在“添加用于”部分中选中“MVC”复选框,然后单击“确定”。

它将创建一个具有最少预定义内容的基本 MVC 项目。

现在我们需要添加一个控制器。

步骤 6 - 右键单击解决方案资源管理器中的控制器文件夹,然后选择“添加”→“控制器”。

它将显示“添加脚手架”对话框。

Right-click Controller Folder

步骤 7 - 选择“MVC 5 控制器 – 带读/写操作”选项。此模板将创建一个带有控制器默认操作的 Index 方法。这也将列出其他方法,例如 Edit/Delete/Create。

步骤 8 - 单击“添加”按钮,将出现“添加控制器”对话框。

Add Employee Controller

步骤 9 - 将名称设置为 EmployeeController 并单击“添加”按钮。

步骤 10 - 您将在 Controllers 文件夹中看到一个新的 C# 文件“EmployeeController.cs”,它在 Visual Studio 中打开以进行编辑,其中包含一些默认操作。

using System;
using System.Collections.Generic;
using System.Linq;

using System.Web;
using System.Web.Mvc;

namespace MVCSimpleApp.Controllers {
   public class EmployeeController : Controller{
      // GET: Employee
      public ActionResult Index(){
         return View();
      }
		
      // GET: Employee/Details/5
      public ActionResult Details(int id){
         return View();
      }
		
      // GET: Employee/Create
      public ActionResult Create(){
         return View();
      }
		
      // POST: Employee/Create
      [HttpPost]
      public ActionResult Create(FormCollection collection){
         try{
            // TODO: Add insert logic here
            return RedirectToAction("Index");
         }catch{
            return View();
         }
      }
		
      // GET: Employee/Edit/5
      public ActionResult Edit(int id){
         return View();
      }
		
      // POST: Employee/Edit/5
      [HttpPost]
      public ActionResult Edit(int id, FormCollection collection){
         try{
            // TODO: Add update logic here
            return RedirectToAction("Index");
         }catch{
            return View();
         }
      }
		
      // GET: Employee/Delete/5
      public ActionResult Delete(int id){
         return View();
      }
		
      // POST: Employee/Delete/5
      [HttpPost]
      public ActionResult Delete(int id, FormCollection collection){
         try{
            // TODO: Add delete logic here
            return RedirectToAction("Index");
         }catch{
            return View();
         }
      }
   }
}

让我们添加一个模型。

步骤 11 - 右键单击解决方案资源管理器中的 Models 文件夹,然后选择“添加”→“类”。

Right-click Models Folder

您将看到“添加新项”对话框。

Add New Item Dialog

步骤 12 - 在中间窗格中选择“类”,并在名称字段中输入 Employee.cs。

步骤 13 - 使用以下代码向 Employee 类添加一些属性。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVCSimpleApp.Models {
   public class Employee{
      public int ID { get; set; }
      public string Name { get; set; }
      public DateTime JoiningDate { get; set; }
      public int Age { get; set; }
   }
}

让我们通过添加另一个方法来更新 EmployeeController.cs 文件,该方法将返回员工列表。

[NonAction]
public List<Employee> GetEmployeeList(){
   return new List<Employee>{
      new Employee{
         ID = 1,
         Name = "Allan",
         JoiningDate = DateTime.Parse(DateTime.Today.ToString()),
         Age = 23
      },
		
      new Employee{
         ID = 2,
         Name = "Carson",
         JoiningDate = DateTime.Parse(DateTime.Today.ToString()),
         Age = 45
      },
		
      new Employee{
         ID = 3,
         Name = "Carson",
         JoiningDate = DateTime.Parse(DateTime.Today.ToString()),
         Age = 37
      },
		
      new Employee{
         ID = 4,
         Name = "Laura",
         JoiningDate = DateTime.Parse(DateTime.Today.ToString()),
         Age = 26
      },
   };
}

步骤 14 - 按以下代码所示更新 index 操作方法。

public ActionResult Index(){
   var employees = from e in GetEmployeeList()
   orderby e.ID
   select e;
   return View(employees);
}

步骤 15 - 运行此应用程序并在浏览器中将 /employee 附加到 URL,然后按 Enter。您将看到以下输出。

Can't Find Index View

如上面的屏幕截图所示,出现错误,此错误实际上非常具有描述性,它告诉我们找不到 Index 视图。

步骤 16 - 因此,要添加视图,请右键单击 Index 操作内部并选择“添加视图”。

Right-click Index Action

它将显示“添加视图”对话框,并将添加默认名称。

Add Default Name

步骤 17 - 从“模板”下拉列表中选择“列表”,从“模型类”下拉列表中选择“Employee”,并取消选中“使用布局页”复选框,然后单击“添加”按钮。

它将在此视图中为您添加一些默认代码。

@model IEnumerable<MVCSimpleApp.Models.Employee>
@{
   Layout = null;
}

<!DOCTYPE html>
<html>
   <head>
      <meta name = "viewport" content = "width = device-width" />
      <title>Index</title>
   </head>
	
   <body>
      <p>@Html.ActionLink("Create New", "Create")</p>
         <table class = "table">
         <tr>
            <th>
               @Html.DisplayNameFor(model => model.Name)
            </th>
				
            <th>
               @Html.DisplayNameFor(model => model.JoiningDate)
            </th>
				
            <th>
               @Html.DisplayNameFor(model => model.Age)
            </th>
				
            <th></th>
         </tr>
			
         @foreach (var item in Model) {
            <tr>
               <td>
                  @Html.DisplayFor(modelItem => item.Name)
               </td>
					
               <td>
                  @Html.DisplayFor(modelItem => item.JoiningDate)
               </td>
					
               <td>
                  @Html.DisplayFor(modelItem => item.Age)
               </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>
   </body>
</html>

步骤 18 - 运行此应用程序,您将收到以下输出。

List of Employees

将显示员工列表。

广告
© . All rights reserved.