ASP.NET MVC - 数据模型

在本章中,我们将讨论在ASP.NET MVC Framework应用程序中构建模型. 模型存储根据来自Controller的命令检索并显示在视图中的数据.

模型是您将使用的类的集合数据和业务逻辑.因此,基本上模型是特定于业务领域的容器.它用于与数据库交互.它还可以用来操作数据来实现业务逻辑.

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

第1步 : 打开Visual Studio.单击File → 新的 → 项目菜单选项.

打开一个新的项目对话框.

打开Visual Studio

第2步 : 从左侧窗格中,选择Templates →  Visual C# → 网站.

第3步 : 在中间窗格中,选择"ASP.NET Web应用程序".

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

MVCSimpleApp

第5步 : 为了简单起见,选择Empty选项并选中'Add folders and core references for'部分中的MVC复选框,然后单击Ok.

它将创建一个基本的MVC项目,其中预定义最少内容.

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

步骤6 : 右键单击解决方案资源管理器中的控制器文件夹,然后选择Add → 控制器.

它将显示Add Scaffold对话框.

<img src ="https://img01.yuandaxia.cn/Content/img/tutorials/asp.net_mvc/rightclick_controller_folder.jpg"alt = "右键单击"控制器文件夹"/>

步骤7 : 选择MVC 5控制器 - 具有读/写操作选项.此模板将创建一个Index方法,其中包含Controller的默认操作.这也将列出其他方法,如编辑/删除/创建.

步骤8 : 单击"添加"按钮,将出现"添加控制器"对话框.

添加员工控制器

第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文件夹,然后选择Add → 类.

右键单击模型文件夹

你会看到添加新项对话框.

添加新项对话框

第12步 : 在中间盘中选择Class并在名称字段中输入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文件,该方法将返回employee列表.

[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 : 更新索引操作方法,如下面的代码所示.

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


第15步 : 运行此应用程序并将/employee附加到浏览器中的URL,然后按Enter键.您将看到以下输出.

找不到索引视图

如上面的屏幕截图所示,出现错误,此错误实际上非常具有描述性,告诉我们无法找到索引视图.

步骤16 : 因此,要添加视图,请在"索引"操作内右键单击并选择"添加视图".

Right-单击索引操作

它将显示"添加视图"对话框,它将添加默认名称.

Add Default Name

步骤17 : 从模板下拉列表和模型类下的员工下拉列表中选择列表,并取消选中"使用布局页面"复选框,然后单击"添加"按钮.

它将为您添加一些默认代码在这个视图中.

@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步 : 运行此应用程序,您将收到以下输出.

员工列表

将显示员工列表.