ASP.Net MVC手腳架

ASP.NET腳手架是ASP.NET Web應用程式的代碼生成框架。 Visual Studio 2013包含用於MVC和Web API專案的預安裝代碼生成器。當想快速添加與數據模型交互的代碼時,可以將腳手架添加到專案中。使用腳手架可以減少在專案中開發標準數據操作的時間。

正如在前面章節教學中所看到的,我們已經為IndexCreateEdit操作創建了視圖,並且還需要更新操作方法。但ASP.Net MVC提供了一種使用腳手架創建所有這些視圖和操作方法的更簡單的方法。

我們來看一個簡單的例子。它創建一個包含模型類 - Employee的相同示例,但是這次將使用腳手架。

第1步 - 打開Visual Studio,然後單擊: -> 新建 -> 專案 菜單選項。一個新的專案對話框打開。
第2步 - 在左側窗格中,選擇:範本 -> Visual C# -> Web
第3步 - 在中間窗格中,選擇“ASP.NET Web應用程式”
第4步 - 在名稱字段中輸入專案名稱:MVCScaffolding ,然後單擊確定 繼續。

將看到下麵的對話框,要求設置ASP.NET專案的初始內容。

第5步 - 為了簡單起見,選擇: 選項,並在為以下項添加檔夾和核心引用’ 中選中MVC 複選框,然後單擊確定

它將使用最少的預定義內容創建一個基本的MVC專案。

專案由Visual Studio創建後,將在“解決方案資源管理器” 窗口中看到許多檔和文件夾。

添加 Entity Framework 支持

第一步是安裝實體框架(Entity Framework)。右鍵單擊該專案,然後選擇:管理NuGet程式包 ,打開NuGet軟體包管理器 。它將打開“NuGet包管理器”,在搜索框中搜索Entity Framework。如下所示 -

選擇實體框架(Entity Framework),然後點擊“安裝(Install)” 按鈕。 它將打開預覽對話框。

點擊確定 繼續下一步 -

點擊“我接受”按鈕開始安裝,完成後如下 -

當實體框架安裝成功後,可看到如上面的截圖所示的出窗口的消息。

添加模型

要添加模型,請右鍵單擊解決方案資源管理器 中的Models 檔夾,然後選擇:添加 -> ,會看到添加新專案 對話框。

在中間平移中選擇:,並在名稱字段中輸入:Employee.cs。如下圖所示 -

使用以下代碼將一些屬性添加到Employee類。

using System;

namespace MVCScaffolding.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模型,現在需要在這個模型類上添加另一個類,它將與實體框架(Entity Framework)進行通信來檢索和保存數據。 以下是Employee.cs檔中的完整代碼。

using System;
using System.Data.Entity;

namespace MVCScaffolding.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是從一個名為DbContextEF類派生的。 在這個類中,有一個名為DbSet的屬性,它基本上代表了要查詢和保存的實體。

添加腳手架專案

要添加腳手架,請右鍵單擊解決方案管理器中的Controllers檔夾,然後選擇:添加 -> 新建搭建基架專案 ,如下圖所示 -

它將顯示“添加腳手架”對話框 -

選擇:包含視圖MVC 5控制器(使用Entity Framework) 項,然後單擊“添加” 按鈕,這將顯示添加控制器對話框。

模型類 下拉列表中選擇:Employee,並從數據上下文類 下拉列表中選擇EmpDBContext。還將看到默認情況下選擇了控制器名稱。

單擊“添加”按鈕繼續,在由Visual Studio使用腳手架創建的EmployeesController中看到以下代碼。

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using MVCScaffolding.Models;

namespace MVCScaffolding.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
        // 為了防止“過多發佈”攻擊,請啟用要綁定到的特定屬性,有關
        // 詳細資訊,請參閱 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
        // 為了防止“過多發佈”攻擊,請啟用要綁定到的特定屬性,有關
        // 詳細資訊,請參閱 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:59083/Employees ,將看到以下輸出結果 -

可以看到視圖中並沒有數據,因為我們還沒有向 Visual Studio 創建的資料庫添加任何記錄。

下麵點擊添加(Create New)鏈接來一個記錄,它將顯示創建視圖,填入相關資訊 -

點擊“創建”按鈕,它將更新Index 視圖,看到有一條記錄。如下所示-

也可以看到新記錄也被添加到資料庫中。

通過上面所看實現步驟可以看到,我們已經通過使用腳手架實現了一個簡單的例子,這是一個用來創建模型類,視圖和動作方法的更容易方式。


上一篇: ASP.Net MVC Web API 下一篇: ASP.Net MVC Bootstrap