ASP.NET MVC - 脚手架

ASP.NET MVC - 脚手架 首页 / ASP.Net MVC入门教程 / ASP.NET MVC - 脚手架

ASP.NET Scaffolding是ASP.NET Web应用程序的代码生成框架, Visual Studio 2013包括针对MVC和Web API项目的预安装代码生成器,当您要快速添加与数据模型交互的代码时,可以将脚手架添加到项目中,使用脚手架可以减少在项目中开发标准数据操作的时间。

让我们看一个简单的示例。我们将创建包含模型类Employee的相同示例,但是这次我们将使用脚手架。

步骤1 -打开Visual Studio,然后单击File→New→Item菜单选项。

将打开一个"New Project"对话框。

New Dialog

步骤2 - 在左侧窗格中,选择Template→Visual C#→Web。

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

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

MVCScaffoldingDemo

步骤5 - 为简单起见,请选择"Empty"选项,然后在"Add folders and core references for"部分中选中" MVC"复选框,然后单击"OK"。

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

无涯教程网

通过Visual Studio创建项目后,您将在"Solution Explorer"窗口中看到许多文件和文件夹。

Project Created by Visual Studio

添加Entity framework

第一步是安装Entity framework。右键单击项目,然后选择NuGet Package Manager→Manage NuGet Packages for Solution…

NuGet Package Manager

它将打开" NuGet Package Manager"。在搜索框中搜索Entity framework。

Entity Framework Search Box

选择Entity framework,然后单击"Install"按钮。它将打开"Preview"对话框。

Open Preview Dialog

单击确定继续。

Click Ok to Continue

点击"I Accept"按钮开始安装。

I Accept Button Installation

一旦安装了Entity framework,您将在输出窗口中看到该消息,如上面的屏幕快照所示。

新增模型

要添加模型,请在Solution Explorer中的Models文件夹上单击鼠标右键,然后选择Add→Class。您会看到"Add New Item"对话框。

Item Dialog

在中间窗格中选择"Class",然后在名称字段中输入Employee.cs。

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

using System;

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

添加DBContext

我们有一个Employee Model,现在我们需要添加另一个类,该类将与Entity Framework通信以检索和保存数据,以下是Employee.cs文件中的完整代码。

using System;
using System.Data.Entity;

namespace MVCScaffoldingDemo.Models{
   public class Employee{
      public int ID { get; set; }
      public string Name { get; set; }
      public DateTime JoiningDate { get; set; }
      public int Age { get; set; }
   }
	
   public class EmpDBContext : DbContext{
      public DbSet<Employee> Employees { get; set; }
   }
}

如您所见," EmpDBContext"是从称为" DbContext"的EF类派生的,在此类中,我们有一个名为DbSet的属性,该属性基本上表示您要查询和保存的实体。

现在,我们来构建解决方案,成功构建项目后,您会看到一条消息。

Project Successfully Build

添加脚手架

要Add Scaffold,请在Solution Explorer中的Controllers文件夹上单击鼠标右键,然后选择"Add"→"New Scaffolded Item"。

New Scaffolded Item

它将显示"Add Scaffold"对话框。

Display Scaffold Dialog

使用中间窗格中的Entity Framework选择带有视图的MVC 5 Controller,然后单击"Add"按钮,这将显示"Add Controller"对话框。

Entity Framework Middle Pane

从"Moel"类下拉列表中选择"Employees",从DBcontext类下拉列表中选择EmpDBContext。您还将看到默认情况下已选择控制器名称。

单击"Add"按钮继续,您将在EmployeesController中看到以下代码,该代码是由Visual Studio使用脚手架创建的。

using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using MVCScaffoldingDemo.Models;

namespace MVCScaffoldingDemo.Controllers {
   public class EmployeesController : Controller{
      private EmpDBContext db = new EmpDBContext();
      
      //GET: Employees
      public ActionResult Index(){
         return View(db.Employees.ToList());
      }
      
      //GET: Employees/Details/5
      public ActionResult Details(int? id){
         if (id == null){
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
         }
			
         Employee employee = db.Employees.Find(id);
			
         if (employee == null){
            return HttpNotFound();
         }
         return View(employee);
      }
      
      //GET: Employees/Create
      public ActionResult Create(){
         return View();
      }
      
      //POST: Employees/Create
      //To protect from overposting attacks, please enable the specific
      properties you want to bind to, for
      //more details see http://go.microsoft.com/fwlink/?LinkId=317598.
      [HttpPost]
      [ValidateAntiForgeryToken]
		
      public ActionResult Create([Bind(Include = "ID,Name,JoiningDate,Age")]
      Employee employee){
         if (ModelState.IsValid){
            db.Employees.Add(employee);
            db.SaveChanges();
            return RedirectToAction("Index");
         }
         return View(employee);
      }
      
      //GET: Employees/Edit/5
      public ActionResult Edit(int? id){
         if (id == null){
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
         }
			
         Employee employee = db.Employees.Find(id);
			
         if (employee == null){
            return HttpNotFound();
         }
         return View(employee);
      }
      
      //POST: Employees/Edit/5
      //To protect from overposting attacks, please enable the specific
      properties you want to bind to, for
      //more details see http://go.microsoft.com/fwlink/?LinkId=317598.
      [HttpPost]
      [ValidateAntiForgeryToken]
      public ActionResult Edit([Bind(Include = "ID,Name,JoiningDate,Age")]Employee employee){
         if (ModelState.IsValid){
            db.Entry(employee).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
         }
         return View(employee);
      }
      
      //GET: Employees/Delete/5
      public ActionResult Delete(int? id){
         if (id == null){
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
         }
			
         Employee employee = db.Employees.Find(id);
			
         if (employee == null){
            return HttpNotFound();
         }
         return View(employee);
      }
      
      //POST: Employees/Delete/5
      [HttpPost, ActionName("Delete")]
      [ValidateAntiForgeryToken]
		
      public ActionResult DeleteConfirmed(int id){
         Employee employee = db.Employees.Find(id);
         db.Employees.Remove(employee);
         db.SaveChanges();
         return RedirectToAction("Index");
      }
      
      protected override void Dispose(bool disposing){
         if (disposing){
            db.Dispose();
         }
			
         base.Dispose(disposing);
      }
   }
}

运行您的应用程序,并指定以下URL http://localhost:59359/employees 。您将看到以下输出。

Run Your Application

您可以看到View中没有数据,因为我们没有向Visual Studio创建的数据库添加任何记录。

通过点击"Create New"链接从浏览器中添加一条记录,它将显示"Create"视图。

Clicking Create New

让我们在以下字段中添加一些数据。

Adding Data in Field

点击"Create"按钮,它将更新索引视图。

Update Index View

您可以看到新记录也已添加到数据库中。

链接:https://www.learnfk.comhttps://www.learnfk.com/asp.net_mvc/asp.net-mvc-scaffolding.html

来源:LearnFk无涯教程网

New Record Added

如您所见,我们通过使用Scaffolding实现了相同的示例,这是从模型类创建Views和Action方法的简便得多的方法。

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

深入浅出区块链 -〔陈浩〕

微服务架构实战160讲 -〔杨波〕

深入浅出云计算 -〔何恺铎〕

数据中台实战课 -〔郭忆〕

Kafka核心源码解读 -〔胡夕〕

手把手带你搭建秒杀系统 -〔佘志东〕

大厂广告产品心法 -〔郭谊〕

现代C++20实战高手课 -〔卢誉声〕

工程师个人发展指南 -〔李云〕

好记忆不如烂笔头。留下您的足迹吧 :)