設計ASP.NET MVC主表明細檢視-1

by vivid 19. 十一月 2014 01:51

.NET Magazine國際中文電子雜誌
者:許薰尹
稿:張智凱
文章編號:N141215501
出刊日期:2014/11/19
開發工具:Visual Studio 2013 Ultimate Update 3
版本:.NET Framework 4.5.X

在ASP.NET MVC的網站應用程式之中,常常會需要整合資料庫,呈現資料庫多個資料表之中的內。另外也需要提供一個使用者介面,讓使用者新增、刪除、修改、查詢資料庫資料。本篇文章將介紹如何建立一個ASP.NET MVC5應用程式,並利用ADO.NET Entity Framework Code First來設計可以呈現Master-Detail(主表明細)檢視的資料存取程式碼。

 

建立ASP.NET MVC 5應用程式專案

我們從建立一個ASP.NET MVC5應用程式專案開始。從Visual Studio 2013開發工具 -「File」-「New」-「Project」,在「New Project」對話盒中,確認視窗上方.NET Framework的目標版本為「.NET Framework 4.5.1」,選取左方「Installed」-「Template」-「Visual C#」程式語言,從「Web」分類中,選取「ASP.NET Web Application」。本例設定專案名稱為「MasterDetailsDemo」,按下「OK」鍵,請參考下圖所示:

clip_image002

圖 1:建立一個ASP.NET MVC5應用程式專案。

在「New ASP.NET Project」對話盒中選取「Empty」項目,勾選下方的「MVC」項目,然後按下「OK」按鈕建立專案,請參考下圖所示:

clip_image004

圖 2:選取「Empty」的「MVC」項目。

安裝Entity Framework套件

預設空白的MVC專案沒有引用Entity Framework,我們可以使用Nuget套件管理員從Nuget.org網站下載「Entity Framework」函式庫。在「Solution Explorer」視窗選取專案名稱。從Visual Studio 2013開發工具「TOOLS」-「Library Package Manager」-「Package Manage Console」開啟「Package Manage Console」視窗,然後在提示字元中輸入install-package指令,並使用「-version」指定安裝Entity Framework 6.1.1版本:

Install-Package EntityFramework -Version 6.1.1

得到的執行結果如下圖所示:

clip_image006

圖 3:使用Nuget套件管理員安裝Entity Framework套件。

設計模型(Model)

首先我們來定義一個Employee模型來描述員工資料,以及一個Department模型來描述部門資訊。部門與員工有一對多的關係。從Visual Studio 2013開發工具-「Solution Explorer」- 專案-「Models」資料夾上方按滑鼠右鍵,從快捷選單選擇「Add」- 「New Item」,開啟「Add New Item」對話盒,從右上方文字方塊輸入「Class」關鍵字搜尋,選取Class,設定名稱為「Employee」,然後按下「Add」按鈕,建立新類別,請參考下圖所示:

clip_image008

圖 4:建立Employee類別。

在Employee類別之中,加入以下程式碼,定義員工該有的屬性,其中DepartmentId 屬性用來和Department模型關聯用,Department屬性用來取得相關聯的部門資訊:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
 
namespace MasterDetailsDemo.Models {
  public class Employee {
    [DisplayName( "員工編號" )]
    public int EmployeeId { get; set; }
   [DisplayName( "部門編號" )]
    public int DepartmentId { get; set; }
 
    [DisplayName( "員工姓名" )]
    public string EmployeeName { get; set; }
    [DisplayName( "生日" )]
    [DisplayFormat( DataFormatString = "{0:yyyy/MM/dd}" , ApplyFormatInEditMode = true )]
    public DateTime BirthDay { get; set; }
    [DisplayName( "已婚" )]
    public bool IsMarried { get; set; }
    [DisplayName( "部門" )]
    public Department Department { get; set; }
  }
}

 

重複上個步驟,新增Department類別來描述部門資料,其中Projects屬性用來描述Department模型相關聯的Employee:

using MasterDetailsDemo.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Entity;
using System.Linq;
using System.Web;
 
namespace MasterDetailsDemo.Models {
 
  public class Department {
    [DisplayName( "部門編號" )]
    public int DepartmentId { get; set; }
    [DisplayName( "部門名稱" )]
    public string DepartmentName { get; set; }
 
    [DisplayName( "員工清單" )]
    public virtual ICollection<Employee> Employees { get; set; }
  }
}

 

選取「Build」-「Build Solution」編譯目前的專案,確認程式碼能正確編譯。

定義DbContext類別

下一步,讓我們來定義DbContext類別,以便利用Entity Framework Code First方式建立以及存取資料庫。從「Models」資料夾上方按滑鼠右鍵,從快捷選單選擇「Add」- 「New Item」,開啟「Add New Item」對話盒,從右上方文字方塊輸入「ado.net」搜尋,選取「ADO.NET Entity Data Model」,設定名稱為「EmployeesContext」,然後按下「Add」按鈕,請參考下圖所示:

clip_image010

圖 5:新增「ADO.NET Entity Data Model」。

下一步,選取「Empty Code First model」項木,建立一個空白的Code First模型(注意:Visual Studio 2013要更新到Update 3才能看到這個選項),請參考下圖所示:

clip_image012

圖 6:建立一個空白的Code First模型。

按下「Finish」按鈕之後,Visual Studio 2013將產生一個EmployeesContext.cs檔案,包含以下的程式碼:

 

namespace MasterDetailsDemo.Models {
  using System;
  using System.Data.Entity;
  using System.Linq;
 
  public class EmployeesContext : DbContext {
    // Your context has been configured to use a 'EmployeesContext' connection string from your application's
    // configuration file (App.config or Web.config). By default, this connection string targets the
    // 'MasterDetailsDemo.Models.EmployeesContext' database on your LocalDb instance.
    //
    // If you wish to target a different database and/or database provider, modify the 'EmployeesContext'
    // connection string in the application configuration file.
    public EmployeesContext( )
      : base( "name=EmployeesContext" ) {
    }
 
    // Add a DbSet for each entity type that you want to include in your model. For more information
    // on configuring and using a Code First model, see http://go.microsoft.com/fwlink/?LinkId=390109.
 
    // public virtual DbSet<MyEntity> MyEntities { get; set; }
  }
 
  //public class MyEntity
  //{
  //    public int Id { get; set; }
  //    public string Name { get; set; }
  //}
}

 

並在Web.config檔案中,加上連結到資料庫的連接字串,目前產生的組態檔是將資料建置在(LocalDB)資料庫:

<connectionStrings>
    <add name="EmployeesContext" connectionString="data source=(LocalDb)\v11.0;initial catalog=MasterDetailsDemo.Models.EmployeesContext;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
  </connectionStrings>

修改EmployeesContext類別的程式碼,在類別中宣告Employees、Departments兩個屬性:

 

  public class EmployeesContext : DbContext {
 
    public EmployeesContext( )
      : base( "name=EmployeesContext" ) {
    }
    public virtual DbSet<Employee> Employees { get; set; }
    public virtual DbSet<Department> Departments { get; set; }
  }

 

選取「Build」-「Build Solution」編譯目前的專案,確認程式碼能正確編譯。

檢視模型

使用Entity Framework Code First方式設計資料存取程式時,因為模型(Model)未來會建置在記憶體之中,不需使用EDMX檔案描述,因此在開發階段看不到模型的長像。你可以安裝Entity Framework Power Tools工具以視覺化的方式檢視模型。從Visual Studio 2013工具的 「Tools」選單,選取「Extensions and Updates」,從「Online」搜尋以及下載「Entity Framework Power Tools Beta4」。

Entity Framework Power Tools工具安裝完成之後,就可以在「Solution Explorer」視窗-專案中的「EmployeesContext.cs」檔案上方按滑鼠右鍵,從快捷選單選擇「Entity Framework」- 「View Entity Data Model(Ready-only)」項目,來檢視模型,請參考下圖所示:

clip_image014

圖 7:檢視模型。

目前的模型,請參考下圖所示:

clip_image016

圖 8:目前的模型。

建立資料庫與初始資料表資料

接下來,我們將使用Entity Framework Code First Migration(資料移轉)方式來建立資料庫與初始資料表資料。從Visual Studio 2013開發工具「TOOLS」-「Library Package Manager」-「Package Manage Console」開啟「Package Manage Console」視窗,然後在提示字元中輸入enable-migrations指令,啟用資料移轉功能:

enable-migrations

得到的執行結果如下圖所示:

clip_image018

圖 9:啟用資料移轉功能。

接著Visual Studio 2013工具會自動在專案中產生一個「Migrations」資料夾,其中包含一個Configuration.cs檔案。我們可改寫其中的Seed方法,建立Department、與Employee物件,這樣就可以利用Entity Framework,新增初始資料到資料庫。注意初始化的程式碼,其中王彼得與李小明將同屬於電腦部,而劉大同則隸屬於會計部:

 
    protected override void Seed( MasterDetailsDemo.Models.EmployeesContext context ) {
 
      Department d1 = new Department {
        DepartmentName = "電腦部" ,
      };
 
      Department d2 = new Department {
        DepartmentName = "會計部" ,
 
      };
      context.Departments.AddOrUpdate(
        e => e.DepartmentName ,
        d1 ,
        d2 ,
        new Department {
          DepartmentName = "業務部" ,
        }
        );
 
      context.Employees.AddOrUpdate(
        e => e.EmployeeName ,
        new Employee {
          EmployeeName = "王彼得" ,
          DepartmentId = 1 ,
          BirthDay = new DateTime( 2010 , 1 , 2 ) ,
          IsMarried = true ,
          Department = d1
        } ,
        new Employee {
          EmployeeName = "李小明" ,
          DepartmentId = 1 ,
          BirthDay = new DateTime( 2011 , 12 , 12 ) ,
          IsMarried = false ,
          Department = d1
        } ,
        new Employee {
          EmployeeName = "劉大同" ,
          DepartmentId = 2 ,
          BirthDay = new DateTime( 2000 , 5 , 6 ) ,
          IsMarried = true ,
          Department = d2
        }
        );
    } 

選取「Build」-「Build Solution」編譯目前的專案,確認程式碼能正確編譯。

更新資料庫

從Visual Studio 2013開發工具「TOOLS」-「Library Package Manager」-「Package Manage Console」開啟「Package Manage Console」視窗,然後在提示字元中輸入update-database,更新資料庫:

update-database

得到的執行結果如下圖所示:

clip_image020

圖 10:更新資料庫。

先驗證資料庫與資料表資料是否正確建立。開啟「Server Explorer」視窗,在「Data Connections」項目上按滑鼠右鍵,從快捷選單之中選取「Add Connection」項目。請參考下圖所示,在「Add Connection」視窗中,設定以下屬性:

  • 資料來源 (Data Source) :Microsoft SQL Server (SQLClient)。
  • Server name欄位:輸入「(localdb)\v11.0」。
  • Log on to server:選取「Use Windows Authentication」。
  • Select or enter a database name欄位:選擇「MasterDetailsDemo.Models.EmployeesContext」資料庫。

完成後按下「OK」按鈕,檢視新建立的資料表與欄位資訊,請參考下圖所示:

clip_image022

圖 11:檢視新建立的資料表與欄位資訊。

展開「Server Explorer」視窗-「Data Connections」-「EmployeesContext」資料庫 -「Tables」- 「Departments」資料表,在「Department」資料表上按滑鼠右鍵,從快捷選單中選取「Show Table Data」顯示Departments資料表所有資料,確認新增了三筆資料:

clip_image024

圖 12:Department資料表所有資料。

在「Departments」資料表上按滑鼠右鍵,從快捷選單中選取「Open Table Definition」,就可以看到Departments資料表的結構描述資訊,其中DepartmentId將是主鍵欄位(Primary Key)請參考下圖所示:

clip_image026

圖 13:Departments資料表的結構描述資訊。

工具利用以下的SQL陳述句來建立資料表,並自動設定一個Primary Key條件約束:

CREATE TABLE [dbo].[Departments] (

    [DepartmentId]   INT IDENTITY (1, 1) NOT NULL,

    [DepartmentName] NVARCHAR (MAX) NULL,

CONSTRAINT [PK_dbo.Departments] PRIMARY KEY CLUSTERED ([DepartmentId] ASC)

);

Employees資料表的內容,請參考下圖所示,將包含三筆資料:

clip_image028

圖 14:檢視Employees資料表的內容。

工具產生的SQL陳述句如下,從中可得知,將利用Employees資料表的DepartmentId欄位與Departments資料表的DepartmentId欄位建立Foreign Key:

CREATE TABLE [dbo].[Employees] (

    [EmployeeId]   INT IDENTITY (1, 1) NOT NULL,

    [DepartmentId] INT NOT NULL,

    [EmployeeName] NVARCHAR (MAX) NULL,

    [BirthDay]     DATETIME NOT NULL,

    [IsMarried]    BIT NOT NULL,

CONSTRAINT [PK_dbo.Employees] PRIMARY KEY CLUSTERED ([EmployeeId] ASC),

CONSTRAINT [FK_dbo.Employees_dbo.Departments_DepartmentId] FOREIGN KEY ([DepartmentId]) REFERENCES [dbo].[Departments] ([DepartmentId]) ON DELETE CASCADE

);

GO

CREATE NONCLUSTERED INDEX [IX_DepartmentId]

ON [dbo].[Employees]([DepartmentId] ASC);

設計控制器(Controller)

接著我們來建立一個EmployeesController來存取資料庫Employees資料表資料。從Visual Studio 2013開發工具-「Solution Explorer」視窗- 專案 -「Controllers」資料夾上方按滑鼠右鍵,從快捷選單選擇「Add」- 「New Scaffolded Item」,開啟「Add Scaffold」對話盒,請參考下圖所示:

clip_image030

圖 15:設計控制器(Controller)。

在「Add Scaffold」對話盒中選取「MVC 5 Controller with views, using Entity Framework」項目,然後按下「Add 」按鈕,請參考下圖所示:

clip_image032

圖 16:選取「MVC 5 Controller with views, using Entity Framework」項目。

在「Add Controller」對話盒中,設定「Model class」為Employee;「Data context class」為「EmployeesContext」;控制器名稱為「EmployeesController」;勾選「Generate views」,然後按下「Add 」按鈕,請參考下圖所示:

clip_image034

圖 17:新增控制器。

Visual Studio 產生的EmployeesController程式如下,裏頭包含基礎的新增、刪除、修改、查詢的Action Method程式碼:

public class EmployeesController : Controller
{
    private EmployeesContext db = new EmployeesContext();
 
    // GET: Employees
    public ActionResult Index()
    {
        var employees = db.Employees.Include( e => e.Department );
        return View( 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()
    {
        ViewBag.DepartmentId = new SelectList( db.Departments, "DepartmentId", "DepartmentName" );
        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 = "EmployeeId,DepartmentId,EmployeeName,BirthDay,IsMarried")] Employee employee )
    {
        if (ModelState.IsValid)
        {
            db.Employees.Add( employee );
            db.SaveChanges();
            return RedirectToAction("Index");
        }
 
        ViewBag.DepartmentId = new SelectList( db.Departments, "DepartmentId", "DepartmentName", employee.DepartmentId );
        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();
        }
        ViewBag.DepartmentId = new SelectList( db.Departments, "DepartmentId", "DepartmentName", employee.DepartmentId );
        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 = "EmployeeId,DepartmentId,EmployeeName,BirthDay,IsMarried")] Employee employee )
    {
        if ( ModelState.IsValid )
        {
            db.Entry( employee ).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        ViewBag.DepartmentId = new SelectList( db.Departments, "DepartmentId", "DepartmentName", employee.DepartmentId );
        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 );
    }
}

 

選取「Build」-「Build Solution」編譯目前的專案,確認程式碼能正確編譯。從「Solution Explorer」視窗- 選取Views\Employees資料夾下的Index.cshtml檔案,按CTRL+F5執行Index 檢視,執行結果參考如下,顯示員工清單,每一筆員工資料前方都會自動顯示所屬部門:

clip_image036

圖 18:顯示員工清單。

Index檢視

工具產生的Index.cshtml內容如下,其中使用「model.Department.DepartmentName」語法,來找到Employee相關聯的Department之DepartmentName:

@model IEnumerable<MasterDetailsDemo.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.Department.DepartmentName )
            </th>
            <th>
                @Html.DisplayNameFor( model => model.EmployeeName )
            </th>
            <th>
                @Html.DisplayNameFor( model => model.BirthDay )
            </th>
            <th>
                @Html.DisplayNameFor( model => model.IsMarried )
            </th>
            <th></th>
        </tr>
   
    @foreach ( var item in Model ) {
        <tr>
            <td>
                @Html.DisplayFor( modelItem => item.Department.DepartmentName )
            </td>
            <td>
                @Html.DisplayFor( modelItem => item.EmployeeName )
            </td>
            <td>
                @Html.DisplayFor( modelItem => item.BirthDay )
            </td>
            <td>
                @Html.DisplayFor( modelItem => item.IsMarried )
            </td>
            <td>
                @Html.ActionLink( "Edit", "Edit", new { id=item.EmployeeId }) |
                @Html.ActionLink( "Details", "Details", new { id=item.EmployeeId }) |
                @Html.ActionLink( "Delete", "Delete", new { id=item.EmployeeId })
            </td>
        </tr>
    }
   
    </table>
</body>
</html>

 

Details檢視

點選Index網頁上任一筆員工後方的「Details」超連結,可以顯示員工詳細資訊,但網頁執行時,預設範本產生的程式碼沒有正確地顯示部門名稱,請參考下圖所示:

clip_image038

圖 19:顯示Details資料。

工具產生的Details.cshtml內容如下:

@model IEnumerable<MasterDetailsDemo.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.Department.DepartmentName)
            </th>
            <th>
                @Html.DisplayNameFor( model => model.EmployeeName)
            </th>
            <th>
                @Html.DisplayNameFor( model => model.BirthDay)
            </th>
            <th>
                @Html.DisplayNameFor( model => model.IsMarried)
            </th>
            <th></th>
        </tr>
   
    @foreach ( var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Department.DepartmentName)
            </td>
            <td>
                @Html.DisplayFor( modelItem => item.EmployeeName)
            </td>
            <td>
                @Html.DisplayFor( modelItem => item.BirthDay)
            </td>
            <td>
                @Html.DisplayFor( modelItem => item.IsMarried)
            </td>
            <td>
                @Html.ActionLink( "Edit", "Edit", new { id=item.EmployeeId }) |
                @Html.ActionLink( "Details", "Details", new { id=item.EmployeeId }) |
                @Html.ActionLink( "Delete", "Delete", new { id=item.EmployeeId })
            </td>
        </tr>
    }
   
    </table>
</body>
</html>

 

我們可以略加修改控制器中的Details方法,利用Include方法,將Employee相關聯的Department資料找出來:

public ActionResult Details(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Employee employee = db.Employees.Include( e => e.Department ).FirstOrDefault(e=>e.EmployeeId==id );
 
    if (employee == null)
    {
        return HttpNotFound();
    }
    return View(employee);
}

 

重新執行程式,則Details檢視的執行結果請參考下圖所示:

clip_image040

圖 20:顯示Details資料。

Edit檢視

若點選Index網頁上任一筆員工後方的「Edit」超連結,可以進入Edit檢視,以編輯員工資訊,工具產生的程式碼很聰明地自動以下拉式清單,來顯示員工所屬的部門名稱,請參考下圖所示:

clip_image042

圖 21:Edit檢視。

Edit檢視的程式碼如下,使用Html.DropDownList顯示下拉式選單:

@model MasterDetailsDemo.Models.Employee
 
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Edit</title>
</head>
<body>
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
       
        <div class="form-horizontal">
            <h4> Employee </h4>
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            @Html.HiddenFor( model => model.EmployeeId)
   
            <div class="form-group">
                @Html.LabelFor( model => model.DepartmentId, "DepartmentId", htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.DropDownList( "DepartmentId", null, htmlAttributes: new { @class = "form-control" })
                    @Html.ValidationMessageFor( model => model.DepartmentId, "", new { @class = "text-danger" })
                </div>
            </div>
   
            <div class="form-group">
                @Html.LabelFor( model => model.EmployeeName, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor( model => model.EmployeeName, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor( model => model.EmployeeName, "", new { @class = "text-danger" })
                </div>
            </div>
   
            <div class="form-group">
                @Html.LabelFor(model => model.BirthDay, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.BirthDay, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.BirthDay, "", new { @class = "text-danger" })
                </div>
            </div>
   
            <div class="form-group">
                @Html.LabelFor(model => model.IsMarried, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    <div class="checkbox">
                        @Html.EditorFor(model => model.IsMarried)
                        @Html.ValidationMessageFor(model => model.IsMarried, "", new { @class = "text-danger" })
                    </div>
                </div>
            </div>
   
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Save" class="btn btn-default" />
                </div>
            </div>
        </div>
    }
   
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
</body>
</html>

 

Delete檢視

若點選Index網頁上任一筆員工後方的「Delete」超連結,可以進入Delete檢視,請參考下圖所示,同樣地,工具產生的程式碼預設不顯示部門名稱,需自行修改,在此不再重複累述。

clip_image044

圖 22:Delete檢視。

Delete檢視的程式碼如下:

@model MasterDetailsDemo.Models.Employee
 
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Delete</title>
</head>
<body>
    <h3>Are you sure you want to delete this?</h3>
    <div>
        <h4>Employee</h4>
        <hr />
        <dl class="dl-horizontal">
            <dt>
                @Html.DisplayNameFor(model => model.Department.DepartmentName)
            </dt>
   
            <dd>
                @Html.DisplayFor(model => model.Department.DepartmentName)
            </dd>
   
            <dt>
                @Html.DisplayNameFor(model => model.EmployeeName)
            </dt>
   
            <dd>
                @Html.DisplayFor(model => model.EmployeeName)
            </dd>
   
            <dt>
                @Html.DisplayNameFor(model => model.BirthDay)
            </dt>
   
            <dd>
                @Html.DisplayFor(model => model.BirthDay)
            </dd>
   
            <dt>
                @Html.DisplayNameFor(model => model.IsMarried)
            </dt>
   
            <dd>
                @Html.DisplayFor(model => model.IsMarried)
            </dd>
   
        </dl>
   
        @using (Html.BeginForm()) {
            @Html.AntiForgeryToken()
   
            <div class="form-actions no-color">
                <input type="submit" value="Delete" class="btn btn-default" /> |
                @Html.ActionLink("Back to List", "Index")
            </div>
        }
    </div>
</body>
</html>

 

Create檢視

最後我們看一下Create檢視,部門的資料同樣採用下拉式選單讓使用者選取,以避免輸入時出錯,請參考下圖所示:

clip_image046

圖 23:Create檢視。

Create檢視的程式碼如下:

@model MasterDetailsDemo.Models.Employee
 
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Create</title>
</head>
<body>
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
       
        <div class="form-horizontal">
            <h4>Employee</h4>
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.DepartmentId, "DepartmentId", htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.DropDownList("DepartmentId", null, htmlAttributes: new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.DepartmentId, "", new { @class = "text-danger" })
                </div>
            </div>
   
            <div class="form-group">
                @Html.LabelFor(model => model.EmployeeName, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.EmployeeName, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.EmployeeName, "", new { @class = "text-danger" })
                </div>
            </div>
   
            <div class="form-group">
                @Html.LabelFor(model => model.BirthDay, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.BirthDay, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.BirthDay, "", new { @class = "text-danger" })
                </div>
            </div>
   
            <div class="form-group">
                @Html.LabelFor(model => model.IsMarried, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    <div class="checkbox">
                        @Html.EditorFor(model => model.IsMarried)
                        @Html.ValidationMessageFor(model => model.IsMarried, "", new { @class = "text-danger" })
                    </div>
                </div>
            </div>
   
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Create" class="btn btn-default" />
                </div>
            </div>
        </div>
    }
   
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
</body>
</html>

 

小結

在這一篇文章中,我們利用Visual Studio 2013的功能,自動產生Entity Framework Code First的資料存取相關程式碼來讀取相關聯的資料表資料。參考下圖,在下一篇文章中,我們將延續這個情境,再新增一個Project模型,以描述Employee與Project之間有一對多的關係。

clip_image048

圖 24:Employee、Department與Project的關係。

評論 (48) -

cours de theatre
cours de theatre United States
2017/9/30 下午 01:27:59 #

Thank you for your blog article.Really looking forward to read more. Really Cool.

回覆

nghi duong vung tau
nghi duong vung tau United States
2017/10/7 上午 01:04:39 #

This is one awesome article post.Thanks Again. Really Cool.

回覆

Osimi seaview
Osimi seaview United States
2017/10/9 下午 06:52:46 #

Hey, thanks for the blog article.Really thank you! Want more.

回覆

Buy illegal backlinks
Buy illegal backlinks United States
2017/10/12 下午 09:31:44 #

Major thanks for the article post. Great.

回覆

dragon city hack pc
dragon city hack pc United States
2017/10/15 下午 04:18:00 #

A round of applause for your article.Much thanks again. Really Great.

回覆

browse around here
browse around here United States
2017/10/17 下午 03:35:27 #

I really enjoy the blog.Thanks Again. Great.

回覆

sletrokor
sletrokor United States
2017/10/17 下午 09:07:38 #

I appreciate you sharing this blog article.Really thank you! Great.

回覆

VigRx
VigRx United States
2017/10/19 上午 08:12:03 #

Great, thanks for sharing this post.Really thank you! Want more.

回覆

Website
Website United States
2017/10/19 下午 07:11:13 #

Very neat article post.Really thank you! Will read on...

回覆

Osimi Sea View
Osimi Sea View United States
2017/10/21 上午 04:28:07 #

Thanks again for the post.Really thank you! Keep writing.

回覆

carte grise en ligne
carte grise en ligne United States
2017/10/21 上午 08:06:44 #

Looking forward to reading more. Great article.Really looking forward to read more. Want more.

回覆

du an osimi
du an osimi United States
2017/10/28 下午 01:00:25 #

Very neat article.Really thank you! Really Cool.

回覆

EZ Battery Reconditioning Review
EZ Battery Reconditioning Review United States
2017/10/30 上午 11:55:19 #

I truly appreciate this article.Really thank you!

回覆

life leadership
life leadership United States
2017/11/1 下午 12:10:19 #

Enjoyed every bit of your blog.Much thanks again.

回覆

phenocal
phenocal United States
2017/11/1 下午 07:43:56 #

wow, awesome article post.Much thanks again. Fantastic.

回覆

phentaslim
phentaslim United States
2017/11/3 下午 02:28:26 #

Thanks a lot for the article post. Great.

回覆

criminel avocat
criminel avocat United States
2017/11/16 下午 07:18:45 #

Fantastic blog post.Much thanks again. Great.

回覆

mobile number location information
mobile number location information United States
2017/11/22 上午 04:01:08 #

I cannot thank you enough for the article.Really looking forward to read more. Keep writing.

回覆

swimwear
swimwear United States
2017/11/23 下午 10:49:03 #

Muchos Gracias for your blog post.Really looking forward to read more. Great.

回覆

Website Developers Auckland
Website Developers Auckland United States
2017/11/25 下午 07:45:14 #

Thanks-a-mundo for the blog post.Really thank you!

回覆

Chad Boonswang and Jeffrey Goodman
Chad Boonswang and Jeffrey Goodman United States
2017/11/26 下午 06:55:11 #

I really enjoy the blog.Much thanks again.

回覆

Chad Boonswang SEO
Chad Boonswang SEO United States
2017/11/27 上午 01:01:59 #

Really appreciate you sharing this post.Thanks Again. Cool.

回覆

scammer wreckers
scammer wreckers United States
2017/11/29 下午 05:25:05 #

Fantastic post. Fantastic.

回覆

can ho go vap
can ho go vap United States
2017/11/30 上午 12:02:56 #

Very good post. Much obliged.

回覆

Credit Mastery builds business credit
Credit Mastery builds business credit United States
2017/12/1 上午 01:49:37 #

wow, awesome article post. Really Great.

回覆

porno
porno United States
2017/12/1 下午 05:31:27 #

Thanks so much for the blog post. Great.

回覆

Build Business Credit
Build Business Credit United States
2017/12/3 上午 05:46:35 #

A big thank you for your blog article. Much obliged.

回覆

Thanks-a-mundo for the article post.Thanks Again. Awesome.

回覆

I appreciate you sharing this blog article.Much thanks again. Keep writing.

回覆

Brian Lezon
Brian Lezon United States
2017/12/14 上午 10:17:24 #

Fantastic article.Really looking forward to read more. Will read on...

回覆

directory
directory United States
2017/12/14 下午 05:10:08 #

I really liked your article.Really thank you! Awesome.

回覆

Christmas Songs
Christmas Songs United States
2017/12/14 下午 11:43:19 #

Very neat article.Thanks Again. Want more.

回覆

canon drivers
canon drivers United States
2017/12/16 下午 06:51:01 #

Appreciate you sharing, great article.Really thank you! Awesome.

回覆

green coffee bean for weight loss
green coffee bean for weight loss United States
2017/12/17 上午 01:10:04 #

Wow, great blog post. Will read on...

回覆

Very good article.Really looking forward to read more. Keep writing.

回覆

IT
IT United States
2017/12/17 下午 06:29:34 #

Thank you for your blog post. Awesome.

回覆

Visit
Visit United States
2017/12/18 上午 01:35:33 #

Major thanks for the blog.Thanks Again. Really Great.

回覆

make cash
make cash United States
2017/12/20 下午 07:45:59 #

Great blog post.Thanks Again. Much obliged.

回覆

canon drivers
canon drivers United States
2017/12/23 下午 01:00:00 #

Wow, great article post.Much thanks again.

回覆

Appreciate you sharing, great blog post. Want more.

回覆

SOCCER HIGHLIGHTS
SOCCER HIGHLIGHTS United States
2017/12/26 下午 02:49:24 #

I cannot thank you enough for the blog.Thanks Again. Really Great.

回覆

hp drivers
hp drivers United States
2018/1/2 下午 01:01:51 #

Muchos Gracias for your blog article.Really thank you! Cool.

回覆

printer driver
printer driver United States
2018/1/3 下午 12:22:44 #

Thanks-a-mundo for the blog.Really looking forward to read more. Much obliged.

回覆

online casino games real money usa
online casino games real money usa United States
2018/1/4 下午 11:15:24 #

I really like and appreciate your blog post.Thanks Again. Really Great.

回覆

hp driver
hp driver United States
2018/1/5 下午 07:37:15 #

Looking forward to reading more. Great article.Really looking forward to read more. Want more.

回覆

FBA
FBA United States
2018/1/6 上午 11:42:29 #

Thanks again for the blog.Really looking forward to read more. Cool.

回覆

colocation chicago
colocation chicago United States
2018/1/10 下午 01:40:27 #

I really like and appreciate your article post.Thanks Again. Really Great.

回覆

新增評論




  Country flag
biuquote
  • 評論
  • 線上預覽
Loading






NET Magazine國際中文電子雜誌

NET Magazine國際中文電子版雜誌,由恆逸資訊創立於2000,自發刊日起迄今已發行超過500篇.NET相關技術文章,擁有超過40000名註冊讀者群。NET Magazine國際中文電子版雜誌希望藉於電子雜誌與NET Developer達到共同學習與技術新知分享,歡迎每一位對.NET 技術有興趣的朋友們多多支持本雜誌,讓作者群們可以有持續性的動力繼續爬文。<請加入免費訂閱>

月分類Month List