搜尋與篩選
NET 搭配 Entity Framework (EF Core) 操作 SQL 資料庫關聯與群組查詢
這份筆記整理了 .NET 搭配 Entity Framework (EF Core) 操作 SQL 資料庫關聯與群組查詢的常見範例。以下是重新整理後的詳細筆記,使用清晰的 Markdown 結構與註解說明,幫助各位未來複習時快速掌握概念。
.NET + SQL 資料表關聯與群組操作筆記¶
一、資料表關聯 (Join)¶
1. 兩個資料表關聯:產品 (Products) 與 類別 (Categories)¶
目標:
顯示所有產品欄位 + 對應的類別名稱,並篩選出「類別編號 = 1」的產品。
var products = ctx.Products.Join(
ctx.Categories,
p => p.CategoryId, // 產品表的關聯欄位
c => c.CategoryId, // 類別表的關聯欄位
(p, c) => new
{
p, // 產品全部欄位
c.CategoryName // 類別名稱
}
).Where(x => x.p.CategoryId == 1) // 篩選條件:類別編號為 1
.ToList();
📘 重點說明:
- Join 方法用來建立兩個資料表的關聯。
- 匿名型別 (p, c) => new { p, c.CategoryName } 同時取兩邊的資料。
- .Where() 為篩選條件。
2. 三個資料表關聯:產品 (Products)、類別 (Categories)、供應商 (Suppliers)¶
目標:
顯示產品資料、類別名稱、供應商公司名稱。
var products = ctx.Products.Join(
ctx.Categories,
p => p.CategoryId,
c => c.CategoryId,
(p, c) => new
{
p, c.CategoryName
}
).Join(
ctx.Suppliers,
product => product.p.SupplierId,
s => s.SupplierId,
(product, s) => new
{
product.p,
product.CategoryName,
s.CompanyName
}
)
.ToList();
📘 重點說明:
- 第二層 Join 時,第一個參數是上一層 Join 的結果。
- 可一次關聯多個資料表,用匿名型別階層展開。
3. 訂單與訂單明細關聯¶
目標:
找出 OrderId = 10251 的訂單,包含訂單資訊與訂單明細。
var products = ctx.Orders.Join(
ctx.OrderDetails,
order => order.OrderId,
orderdetail => orderdetail.OrderId,
(order, orderdetail) => new
{
order.OrderId,
order.CustomerId,
order.EmployeeId,
order.OrderDate,
orderdetail
}
).Where(x => x.OrderId == 10251)
.ToList();
📘 重點說明:
- 一對多關聯:一筆訂單對應多筆訂單明細。
- 將所有明細以 .Join 取出後可搭配條件過濾。
二、群組運算 (GroupBy)¶
1. 單欄位群組統計¶
範例:
計算每個群組的產品數量。
var groupCounts = context.Products
.GroupBy(p => p.GroupId)
.Select(g => new
{
GroupId = g.Key, // 群組依據欄位
Count = g.Count() // 各群組數量
})
.ToList();
📘 用法:
GroupBy() 將資料依欄位分組,Select() 可對群組進行聚合 (如 .Count(), .Sum(), .Average() 等)。
2. 群組練習:每個縣市的客戶數¶
var cuscount = ctx.Customers
.GroupBy(x => x.City)
.Select(x => new
{
縣市 = x.Key,
個數 = x.Count()
})
.ToList();
3. 多欄位群組¶
範例:
同時依 GroupId 和 Price 兩欄位群組,並計算同組價格總和。
var groupedData = context.Products
.GroupBy(e => new { e.GroupId, e.Price }) // 多欄位群組
.Select(g => new
{
g.Key.GroupId,
g.Key.Price,
TotalSum = g.Sum(e => e.Price)
})
.ToList();
📘 重點說明:
- new { e.GroupId, e.Price } 建立複合鍵群組。
- 群組後可以針對組內資料進行加總或統計。
三、日期時間欄位處理¶
範例:
從 OrderDate 中取出年份。
var y = ctx.Orders
.Select(x => new
{
x.OrderDate,
x.OrderDate.Value.Year
})
.ToList();
📘 重點說明:
- .Value.Year 適用於 DateTime? (可為 null) 欄位。
- 可用於後續群組或篩選條件。
四、綜合練習:計算每個客戶每年銷售總金額¶
1. 關聯 Customers → Orders → OrderDetails¶
var sales = ctx.Customers.Join(
ctx.Orders,
customer => customer.CustomerId,
order => order.CustomerId,
(customer, order) => new
{
customer.CompanyName,
order.OrderId,
order.OrderDate
}).Join(
ctx.OrderDetails,
order => order.OrderId,
orderdetail => orderdetail.OrderId,
(order, orderdetail) => new
{
order,
orderdetail
}
)
.OrderBy(x => x.order.OrderDate)
.ToList();
2. 最終整合:群組計算每年每客戶銷售額¶
var sales = ctx.Customers.Join(
ctx.Orders,
customer => customer.CustomerId,
order => order.CustomerId,
(customer, order) => new
{
customer.CompanyName,
order.OrderId,
order.OrderDate
}).Join(
ctx.OrderDetails,
order => order.OrderId,
orderdetail => orderdetail.OrderId,
(order, orderdetail) => new
{
order,
orderdetail
}
).GroupBy(x => new { x.order.CompanyName, Year = x.order.OrderDate.Value.Year })
.Select(x => new
{
x.Key.CompanyName,
x.Key.Year,
銷售額 = x.Sum(x =>
(Convert.ToDouble(x.orderdetail.Quantity) *
Convert.ToDouble(x.orderdetail.UnitPrice) *
(1 - x.orderdetail.Discount)))
})
.OrderBy(x => x.CompanyName)
.ThenBy(x => x.Year)
.ToList();
📘 邏輯分解:
1. 第一層 Join: 將客戶與訂單連接。
2. 第二層 Join: 將訂單與訂單明細連接。
3. GroupBy: 依「客戶名稱 + 年份」分組。
4. Sum(): 銷售總額公式 = 數量 * 價格 * (1 - 折扣)。
5. 排序: 先按客戶名稱,再按年度排序輸出。
2025/11/27 SQL練習
新增記事本資料表 SQL 語法¶
使用 SQL Server 建立記事本資料表 Notes,欄位說明如下:
- Id 欄位為主鍵且自動遞增。
- ndate 為日期時間欄位,預設為當前系統時間 (getdate())。
- content 為記事內容文字,容納最多 300 字。
CREATE TABLE [dbo].[Notes]
(
[Id] INT NOT NULL PRIMARY KEY IDENTITY,
[ndate] DATETIME NULL DEFAULT getdate(),
[content] NVARCHAR(300) NULL
)
此資料表設計適用於儲存簡單的記事與時間戳記。
Entity Framework Core 資料查詢範例¶
- 全部欄位撈取,無篩選條件
var notes = ctx.Notes.ToList();
直接取得 Notes 資料表中所有資料。
- 單一欄位撈取,無篩選條件
var notes = ctx.Notes.Select(x => x.Content).ToList();
只取得 Content 欄位資料。
- 多欄位撈取,可更改欄位名稱
var notes = ctx.Notes.Select(x => new { x.Id, 內容 = x.Content }).ToList();
撈取多個欄位且結果中欄位名稱可自訂(例如將 Content 改為 內容)。
- 有條件篩選及全部欄位
以北風資料庫為例,查詢「台北市」且「北平區」的客戶:
var c = ctx.Customers.Where(x => x.City == "台北市" && x.Region == "北平區").ToList();
- 排序查詢(兩個鍵值排序)
var c = ctx.Customers.OrderBy(x => x.City).ThenByDescending(x => x.Region).ToList();
主鍵值以城市排序,再以區域降冪排序。
刪除資料範例¶
- 刪除單筆資料
先使用 Find(鍵值) 找到該筆資料,接著用 Remove 從 DbContext 移除,最後呼叫 SaveChanges 實際刪除資料。
var n = ctx.Notes.Find(鍵值);
ctx.Notes.Remove(n);
ctx.SaveChanges();
- 刪除多筆資料
使用 Where 找出多筆符合條件的資料,再用 RemoveRange 一次刪除。
var n = ctx.Notes.Where(x => x.Id == 1 || x.Id == 3).ToList();
ctx.Notes.RemoveRange(n);
ctx.SaveChanges();
- 結合刪除與查詢
在 Controller Index(int id) 中,如果傳入了 id,先刪除該資料筆數,之後讀取所有資料並透過 ViewBag 傳到 View:
public IActionResult Index(int id)
{
using (var ctx = new FinalDBContext())
{
if(id != 0)
{
var n = ctx.Notes.Find(id);
ctx.Remove(n);
ctx.SaveChanges();
}
var notes = ctx.Notes.ToList();
ViewBag.notes = notes;
return View();
}
}
Razor View 展示記事本資料¶
頁面中用 foreach 列出所有記事資料(時間、內容),並在每筆記錄後面附上刪除按鈕。刪除按鈕使用 <form> POST 傳送該筆記事的 Id,送到相同的 Index Action。
@{
ViewData["Title"] = "Home Page";
var notes = ViewBag.notes;
}
<div class="text-center">
<div class="container w-75">
<table class="table">
<thead>
<tr>
<th>時間</th>
<th>內容</th>
<th>動作</th>
</tr>
</thead>
<tbody>
@foreach(var n in notes)
{
<tr>
<td>@n.Ndate.ToString("yyyy-MM-dd, HH:mm")</td>
<td>@n.Content</td>
<td>
<form action="~/Home/Index" method="post">
<button type="submit" class="btn btn-danger" name="id" value="@n.Id">刪除</button>
</form>
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
這種做法透過表單提交,讓使用者能直接點擊刪除按鈕刪除特定記錄。
相關教學資源¶
- 老師的教學網站(FlipClass):https://flipclass.stust.edu.tw/media/doc/346303
- 範例示範網頁(心情記事本):https://dashboard.coffeeshoptw.com/notes/note/22
這些資源可做為課堂內容的補充與範例參考。
以上為這堂課主要內容精要整理,涵蓋資料表設計、資料查詢與刪除,以及 Razor View 顯示的實作方式,幫助理解 ASP.NET Core MVC 開發中常見的資料存取與呈現流程。若需要更進一步範例與說明,可參考上述教學頁面。
Microsoft SQL + cshtml 教學
一、建立 Notes 資料表
在 SQL Server 中,先建立一個簡單的備忘錄資料表 Notes,用來練習 INSERT / SELECT 等基本指令。learn.microsoft+1
-
使用 CREATE TABLE 建立資料表。
-
使用 IDENTITY 做流水號主鍵,DEFAULT getdate() 自動寫入建立時間。
範例指令可寫成:
CREATE TABLE [dbo].[Notes]
(
[Id] INT NOT NULL PRIMARY KEY IDENTITY,
[ndate] DATETIME NULL DEFAULT getdate(),
[content] NVARCHAR(300) NULL
);
執行後,dbo 底下會多出 Notes 資料表,之後可以用 EF Core 做對應模型來練習 CRUD。learn.microsoft
二、在 SQL Server 建立與連接資料庫
這一段說明如何在 Visual Studio/SSDT 介面中建立 Northwind 資料庫,並準備給 EF Core 使用。marcus116.blogspot+1
-
開啟 SQL Server 物件總管
-
在 Visual Studio 上方選單:檢視 → SQL Server 物件總管。
-
在左側 SQL Server 節點上按右鍵,可選「加入 SQL Server」或「中斷連接」,設定你的伺服器連線。
-
-
用 SQL 指令建立 Northwind
-
在 SQL Server 物件總管中,對你的伺服器按右鍵 → 新增查詢。
-
將 Northwind 的 .sql 腳本內容貼入查詢視窗,按執行,建立所有資料表與資料。jetbrains
-
-
用附加方式加入現有資料庫檔案
-
檢視 → 資料庫總管 → 資料連接 → 加入連接。
-
選擇「Microsoft SQL Server 資料庫檔案」,指定 .mdf 檔,即可將現有的 Northwind 加入到工具中。uuu
-
完成後,SQL Server 中已經有 Northwind 與 Notes,可以進入 EF Core 步驟。
三、在專案安裝 Entity Framework Core 套件
Entity Framework Core 是一套物件關聯對應(O/R Mapping)工具,能用 C# 類別代表資料表,而不是直接手寫 SQL。uuu+1
-
在 Visual Studio:工具 → NuGet 套件管理員 → 管理解決方案的 NuGet 套件。
-
切到「瀏覽」頁籤並安裝:
-
Microsoft.EntityFrameworkCore.SqlServer
-
Microsoft.EntityFrameworkCore.Tools
-
因為教室環境使用 .NET 8.0 SDK,請選擇 9.0.xx 對應版本;若要用最新 EF Core 版本,需先更新 .NET SDK 版本。marcus116.blogspot
四、用 Scaffold-DbContext 反向產生模型與 Context
接下來用「資料庫優先(Database First)」方式,從現有的 Northwind 資料庫自動產生 C# 類別與 DbContext。jetbrains+1
-
開啟套件管理器主控台
-
工具 → NuGet 套件管理員 → 套件管理器主控台。
-
-
輸入反向工程指令(範例)
Scaffold-DbContext `
-Connection "Server=(localdb)\MSSQLLocalDB;Database=Northwind;Trusted_Connection=True;" `
Microsoft.EntityFrameworkCore.SqlServer `
-OutputDir Models `
-Force `
-Context NorthwindDBContext
-
Server:本機 LocalDB 伺服器 (localdb)\MSSQLLocalDB。
-
Database:Northwind。
-
Trusted_Connection=True 表示使用 Windows 登入,可省略 User ID / Password。
-
-OutputDir 指定資料表模型類別輸出到 Models 資料夾。
-
-Context 指定 DbContext 類別名稱為 NorthwindDBContext。uuu+1
執行後,專案會多出一個 NorthwindDBContext 類別以及多個資料表對應的模型(Customers、Orders、Products 等),之後控制器就能透過它存取資料庫。jetbrains
五、在控制器使用 DbContext 讀取資料
所有範例都遵守同一個模式:建立 DbContext → 對 context.資料表 操作 → ToList() 取得清單 → 傳給 View。uuu+1
基本範例:取得所有客戶資料 Customers
public IActionResult Index()
{
using (var ctx = new NorthwindDBContext())
{
List<Customer> c = ctx.Customers.ToList();
return View(c);
}
}
-
ctx.Customers 代表 Customers 資料表。
-
ToList() 將查詢結果轉成 List。
-
View(c) 將資料清單傳入 Index.cshtml。
在 Index.cshtml 中,宣告模型並顯示:
@model List
| 名稱 | 縣市 | 地址 | 聯絡人 |
|---|---|---|---|
| @c.CompanyName | @c.City | @c.Address | @c.ContactName |
這樣就完成最基本的「讀取全部資料表資料並顯示在網頁」的流程。jetbrains
六、依條件篩選:Where 與 DropDown 選單
使用 LINQ 的 Where 來實作「依縣市篩選客戶」的功能,搭配下拉選單讓使用者選擇 City。learn.microsoft+1
控制器 Index 動作(帶 city 參數):
public IActionResult Index(string city)
{
using (var ctx = new NorthwindDBContext())
{
var cities = ctx.Customers
.Select(x => x.City)
.Distinct()
.ToList();
var customers = ctx.Customers
.Select(x => new {
公司名稱 = x.CompanyName,
x.Address,
x.City,
x.ContactName,
x.Phone
})
.Where(x => x.City == city)
.ToList();
ViewBag.customers = customers;
ViewBag.cities = cities;
return View();
}
}
-
Select(x => x.City).Distinct() 先取出所有城市再去除重複。
-
Where(x => x.City == city) 篩選某一個城市的客戶。
Index.cshtml 畫面:
@{
var cities = ViewBag.cities as List;
var customers = ViewBag.customers;
}
| 公司名稱 | 聯絡人 | 縣市 | 地址 | 電話 |
|---|---|---|---|---|
| @c.公司名稱 | @c.ContactName | @c.City | @c.Address | @c.Phone |
這樣就完成「選擇縣市 → 顯示指定城市客戶資料」的互動式查詢畫面。jetbrains
七、選取部分欄位與計算欄位(Select)
實務上常常只需要部分欄位,或需要額外的計算欄位,可以用 Select 搭配匿名型別達成。learn.microsoft+1
-
取出產品表 ProductName 與 UnitPrice 欄位:
using (var ctx = new NorthwindDBContext())
{
var data = ctx.Products
.Select(x => new { x.ProductName, x.UnitPrice })
.ToList();
return View(data);
}
-
修改欄位顯示名稱(匿名型別自訂屬性名稱):
using (var ctx = new NorthwindDBContext())
{
var data = ctx.Products
.Select(x => new {
產品名稱 = x.ProductName,
單價 = x.UnitPrice
})
.ToList();
return View(data);
}
-
選取計算欄位,例如訂單明細金額 = 數量 × 單價 × (1 − 折扣):
using (var ctx = new NorthwindDBContext())
{
var data = ctx.OrderDetails
.Select(x => new {
x.Quantity,
x.UnitPrice,
x.Discount,
金額 = Convert.ToSingle(x.Quantity) *
Convert.ToSingle(x.UnitPrice) *
(1 - x.Discount)
})
.ToList();
return View(data);
}
這些 Select 操作對應到 SQL 的 SELECT 子句:指定欄位與運算欄位,用 LINQ 寫起來更直觀。learn.microsoft
八、Distinct、OrderBy、GroupBy 等常用查詢
SQL 中常見的 GROUP BY、ORDER BY、DISTINCT 在 LINQ 中分別對應 GroupBy、OrderBy、Distinct 等方法。w3schools+2
-
取得不重複的國家列表(Distinct):
using (var ctx = new NorthwindDBContext())
{
var countries = ctx.Customers
.Select(x => x.Country)
.Distinct()
.ToList();
return View(countries);
}
-
篩選德國客戶(Where):
using (var ctx = new NorthwindDBContext())
{
var germanCustomers = ctx.Customers
.Where(x => x.Country == "Germany")
.ToList();
return View(germanCustomers);
}
-
排序與群組(OrderBy / GroupBy)概念:
-
context.資料表.OrderBy(x => x.欄位) 對應 SQL 的 ORDER BY 欄位。
-
context.資料表.GroupBy(x => x.欄位) 對應 SQL 的 GROUP BY 欄位。
-
GroupBy(x => new { 名稱 = x.欄位 }) 可同時依多個欄位分組,類似 SQL 中 GROUP BY 欄位1, 欄位2。digitalocean+2
-
了解這些對應關係,可以更輕鬆從 LINQ 推回 SQL 的執行邏輯。
九、練習題:Products、Orders、Employees
以下練習可以放在 TinyMCE 編輯器中當作課堂作業步驟。
-
取得所有產品資料 Products:
控制器:
public IActionResult Index()
{
using (var ctx = new NorthwindDBContext())
{
var p = ctx.Products.ToList();
return View(p);
}
}
View(Index.cshtml):
@model List
| 產品名稱 | 供應商編號 | 單價 | 庫存 |
|---|---|---|---|
| @p.ProductName | @p.SupplierId | @p.UnitPrice | @p.UnitsInStock |
-
取得所有訂單資料 Orders:
-
請在控制器中撰寫 var o = ctx.Orders.ToList();
-
建立對應的 Index.cshtml,顯示訂單編號、客戶編號、員工編號、訂單日期等欄位。
-
-
取得所有員工資料 Employees:
控制器:
public IActionResult Index()
{
using (var ctx = new NorthwindDBContext())
{
var e = ctx.Employees.ToList();
return View(e);
}
}
View(卡片顯示):
@model List
@e.LastName, @e.FirstName
@e.Address
@e.HomePhone
這些練習涵蓋了 EF Core 中最常用的 ToList() 查詢與 View 資料綁定流程。uuu+1
十、CRUD 方法與 Join 進階查詢
EF Core 提供一組標準方法對應新增、更新、刪除與儲存動作。uuu+1
常見方法對照:
-
Add / AddAsync / AddRange / AddRangeAsync:新增資料,需搭配 SaveChanges() 或 SaveChangesAsync()。
-
Update / UpdateRange:更新資料後,呼叫 SaveChanges()。
-
Remove / RemoveRange:刪除資料後,呼叫 SaveChanges()。
-
SaveChanges / SaveChangesAsync:將變更寫入資料庫。
此外還可以使用 Join 撰寫多表查詢,對應到 SQL 的 INNER JOIN。learn.microsoft+1
範例 1:Authors 與 Books 兩表 Join
using (var context = new BookStore())
{
var data = context.Authors
.Join(
context.Books,
author => author.AuthorId,
book => book.Author.AuthorId,
(author, book) => new
{
BookId = book.BookId,
AuthorName = author.Name,
BookTitle = book.Title
}
)
.ToList();
}
範例 2:三表 Join(Authors、AuthorBiographies、Books)
using (var context = new BookStore())
{
var authorsData = context.Authors
.Join(
context.AuthorBiographies,
author => author.AuthorId,
authorBio => authorBio.AuthorBiographyId,
(author, authorBio) => new
{
AuthorId = author.AuthorId,
Name = author.Name,
Biography = authorBio.Biography
}
)
.Join(
context.Books,
author => author.AuthorId,
book => book.BookId,
(author, book) => new
{
AuthorId = author.AuthorId,
Name = author.Name,
Biography = author.Biography,
BookTitle = book.Title
}
)
.ToList();
}
這些 Join 寫法在 LINQ 中對應 SQL JOIN 子句,是從多個資料表組合資料的重要技巧。learn.microsoft+1
... - https://learn.microsoft.com/en-us/sql/t-sql/queries/select-group-by-transact-sql?view=sql-server-ver17
- https://learn.microsoft.com/zh-tw/sql/t-sql/queries/select-examples-transact-sql?view=sql-server-ver17
- https://marcus116.blogspot.com/2019/04/netcore-entity-framework-core-crud-intro.html
- https://www.uuu.com.tw/Public/content/article/20/20200413.htm
- https://blog.jetbrains.com/dotnet/2023/07/20/reverse-engineering-existing-databases-with-entity-framework-core/
- https://www.w3schools.com/sql/sql_groupby.asp
- https://www.digitalocean.com/community/tutorials/how-to-use-groupby-and-orderby-in-sql
- https://www.tiny.cloud/docs/tinymce/latest/add-css-options/
- https://www.tiny.cloud/blog/tinymce-css-and-custom-styles/
- https://www.tiny.cloud/docs/tinymce/latest/editor-content-css/
- https://stackoverflow.com/questions/17701783/tinymce-multiple-css-classes
- https://www.tiny.cloud/blog/css-hacks/
- https://www.tiny.cloud/docs/tinymce/latest/content-formatting/
- https://ithelp.ithome.com.tw/m/articles/10262110
- https://forum.backdropcms.org/forum/add-css-classes-tinymce-editor
- https://processwire.com/talk/topic/501-css-classes-in-tinymce/
- https://www.datacamp.com/tutorial/group-by-having-clause-sql
- https://dev.to/codeanddeploy/tinymce-add-customcontent-css-example-5b5i
- https://stackoverflow.com/questions/79632710/how-to-use-windows-authentication-with-the-scaffold-dbcontext-command
- https://stackoverflow.com/questions/43453120/creating-new-table-from-select-statement
2025-11-20 資料庫操作
老師資源¶
https://flipclass.stust.edu.tw/media/doc/345156
取出所有客戶資料¶
Index動作¶
public IActionResult Index(string city)
{
using (var ctx=new NorthwindDBContext())
{
var cities = ctx.Customers.Select(x => x.City).Distinct().ToList();
var customers = ctx.Customers.Select(x=>new { 公司名稱=x.CompanyName, x.Address, x.City, x.ContactName, x.Phone }).Where(x=>x.City==city).ToList();
ViewBag.customers = customers;
ViewBag.cities = cities;
return View();
}
}
Index畫面¶
<div class="text-center">
<div>
<form action="~/Home/Index" method="post">
縣市
<select name="city">
@foreach (var d in cities)
{
<option value="@d">@d</option>
}
</select>
<button type="submit" class="btn btn-primary">選擇</button>
</form>
</div>
<div class="container w-75">
<table class="table">
<thead>
<tr>
<th scope="col">公司名稱</th>
<th scope="col">聯絡人</th>
<th scope="col">縣市</th>
<th scope="col">地址</th>
<th scope="col">電話</th>
</tr>
</thead>
<tbody>
@foreach (var c in customers)
{
<tr>
<td>@c.公司名稱</td>
<td>@c.ContactName</td>
<td>@c.City</td>
<td>@c.Address</td>
<td>@c.Phone</td>
</tr>
}
</tbody>
</table>
</div>
</div>
1. 開啟資料庫伺服器¶
選擇專案 檢視-SQL SERVER物件總管
點選SQL SERVER 按下滑鼠右鍵 選擇 加入SQL Server 或中斷連接
2. 建立資料庫(使用sql命令)¶
點選 SQL SERVER 按下滑鼠右鍵 選擇 新增查詢
將附檔Northwindsql命令內容複製並貼於新增查詢頁面 後執行
3. 建立資料庫(使用附加方式)¶
選擇 檢視-資料庫總管-資料連接-加入連接-MS SQL Server資料庫檔案
4. 在專案安裝 Entity Framework套件¶
Entity Framework(又名ADO.NET Entity Framework)是微軟以ADO.NET為基礎所發展出來的物件關聯對應(O/R Mapping)的解決方案,使用者不直接與資料庫互動,而是藉由Entity Framework物件與資料庫進行互動。
請開啟 工具-NuGet套件管理員-管理方案NuGet套件,點選瀏覽並安裝下列二項套件(因為電腦教室使用 .Net 8.0 sdk,請選擇 9.0.xx版本)-如果要使用最新版請更新 .Net SDK:
- Microsoft.EntityFrameworkCore.SqlServer
- Microsoft.EntityFrameworkCore.Tools
5. 執行Entity Framework套件命令建立對應資料庫資料表資料類型及連接 Context 檔案¶
選擇 工具-NuGet套件管理員-套件管理器主控台,並輸入
Scaffold-DbContext -Connection "Server=資料庫伺服器;Database=資料庫名稱;Trusted_Connection=True; User ID=資料庫伺服器名稱;Password=資料庫伺服器密碼" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Force -Context 資料庫名稱DBContext
- 若資料庫伺服器為
(localdb)\MSSQLLocalDB - 資料庫名稱為 Northwind
- 本地端登入帳號可移除 User ID 及 Password
-OutputDir設定資料表資料模型檔案輸出位置-Context用於設定資料庫連接檔案名稱
範例:
Scaffold-DbContext -Connection "Server=(localdb)\MSSQLLocalDB;Database=Northwind;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Force -Context NorthwindDBContext
6. 資料庫操作¶
控制器-動作使用下列命令連接並執行資料庫操作:
using (var ctx=new 資料庫Context())
{
var c = ctx.資料模型.ToList();
return View();
}
範例:取得所有客戶資料並轉為清單存在變數 c:
using (var ctx = new NorthwindDBContext())
{
var c = ctx.Customers.ToList();
return View(c);
}
練習¶
I Index動作¶
public IActionResult Index()
{
using (var ctx=new NorthwindDBContext())
{
List<Customer> c = ctx.Customers.ToList();
return View(c);
}
}
Index.cshtml 檢視頁面¶
<div class="container w-75">
<table class="table">
<thead>
<tr>
<th scope="col">名稱</th>
<th scope="col">縣市</th>
<th scope="col">地址</th>
<th scope="col">聯絡人</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</div>
1. 請取得所有產品資料 (Products)¶
Index動作¶
public IActionResult Index()
{
using (var ctx=new NorthwindDBContext())
{
var p = ctx.Products.ToList();
return View(p);
}
}
Index畫面¶
@model List<WebApplication1.Models.Product>
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<div class="container">
<table class="table">
<thead>
<tr>
<th scope="col">產品名稱</th>
<th scope="col">供應商編號</th>
<th scope="col">單價</th>
<th scope="col">庫存</th>
</tr>
</thead>
<tbody>
@foreach (var p in Model)
{
<tr>
<th scope="row">@p.ProductName</th>
<td>@p.SupplierId</td>
<td>@p.UnitPrice</td>
<td>@p.UnitsInStock</td>
</tr>
}
</tbody>
</table>
</div>
</div>
2. 請取得所有訂單資料 (Orders)¶
3. 請取得所有員工資料 (Employees)¶
Index動作¶
public IActionResult Index()
{
using (var ctx = new NorthwindDBContext())
{
var c = ctx.Employees.ToList();
return View(c);
}
}
Index檢視檔¶
@model List<WebApplication2.Models.Employee>
@{
ViewData["Title"] = "Home Page";
}
<div class="container">
<div class="row">
@foreach (var e in Model)
{
<div class="col-4">
<div class="card">
<img src="~/imgs/pic.jpg" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">@e.LastName, @e.FirstName</h5>
<p class="card-text">@e.Address</p>
<p class="card-text">@e.HomePhone</p>
</div>
</div>
</div>
}
</div>
</div>
選取部分欄位¶
透過 Select 命令設定取得欄位,請注意 x=> 為 Lambda 表示式,x 代表資料表每一筆紀錄。
下列命令取出產品資料表 ProductName 與 UnitPrice 欄位:
using (var ctx = new NorthwindDBContext())
{
var c = ctx.Products.Select(x=>new {x.ProductName,x.UnitPrice}).ToList();
return View();
}
修改選取欄位名稱(在欄位前設定新名稱)¶
using (var ctx = new NorthwindDBContext())
{
var c = ctx.Products.Select(x=>new {產品名稱=x.ProductName,x.UnitPrice}).ToList();
return View();
}
選取計算欄位¶
using (var ctx = new NorthwindDBContext())
{
var c = ctx.OrderDetails.Select(x=>new {x.Quantity,x.UnitPrice,x.Discount, 金額=Convert.ToSingle(x.Quantity)*Convert.ToSingle(x.UnitPrice)*(1-x.Discount)}).ToList();
return View();
}
練習¶
- 取出客戶資料表 Customers 中 CustomerName, City, Country 欄位
- 取出員工資料表 Employees 中 LastName, FirstName, HomePhone 欄位
context.資料表.First()¶
context.資料表.Select(x=>x.欄位)¶
public IActionResult Index()
{
using (var ctx = new NorthwindDBContext())
{
var c = ctx.Customers.Select(x => x.Country).ToList();
return View(c);
}
//return View();
}
public IActionResult Index()
{
using (var ctx = new NorthwindDBContext())
{
var c = ctx.Customers.Select(x => new { x.Country, x.City}).ToList();
return View(c);
}
//return View();
}
public IActionResult Index()
{
using (var ctx = new NorthwindDBContext())
{
var c = ctx.Customers.Select(x => x.Country).Distinct().ToList();
return View(c);
}
//return View();
}
context.資料表.Where(x=>x.欄位==‘值’)¶
德國(Germany)客人:
using (var ctx=new NorthwindDBContext())
{
var c = ctx.Customers.Where(x=>x.Country=="Germany").ToList();
return View(c);
}
context.資料表.OrderBy(x=>x.欄位)¶
context.資料表.GroupBy(x=>x.欄位)¶
context.資料表.GroupBy(x=>new {名稱=x.欄位})¶
context.資料表.OrderBy(x=>x.欄位1).ThenOrderBy(x=>x.欄位2)¶
context.資料表.ToList()¶
public IActionResult Index()
{
using (var ctx = new NorthwindDBContext())
{
var c = ctx.Employees.ToList();
return View(c);
}
//return View();
}
Razor 範例¶
@model List<Employee>
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
@foreach (Employee e in Model)
{
<h3>@e.FirstName</h3>
}
</div>
資料庫 CRUD 方法與用法¶
| 方法 | Usage |
|---|---|
| Add | 新增必須執行 SaveChanges() |
| AddAsync | 新增必須執行 SaveChanges() |
| AddRange | 新增必須執行 SaveChanges() |
| AddRangeAsync | 新增必須執行 SaveChanges() |
| Remove | 移除必須執行 SaveChanges() |
| RemoveRange | 移除必須執行 SaveChanges() |
| SaveChanges | 儲存 |
| SaveChangesAsync | 非同步儲存 |
| Update | 更新必須執行 SaveChanges() |
| UpdateRange | 更新必須執行 SaveChanges() |
Join 範例 1¶
using (var context = new BookStore())
{
var data = context.Authors
.Join(
context.Books,
author => author.AuthorId,
book => book.Author.AuthorId,
(author, book) => new
{
BookId = book.BookId,
AuthorName = author.Name,
BookTitle = book.Title
}
).ToList();
}
Join 範例 2¶
using (var context = new BookStore())
{
var authorsData = context.Authors
.Join(
context.AuthorBiographies,
author => author.AuthorId,
authorBio => authorBio.AuthorBiographyId,
(author, authorBio) => new
{
AuthorId = author.AuthorId,
Name = author.Name,
Biography = authorBio.Biography
}
)
.Join(
context.Books,
author => author.AuthorId,
book => book.BookId,
(author, book) => new
{
AuthorId = author.AuthorId,
Name = author.Name,
Biography = author.Biography,
BookTitle = book.Title
}
)
.ToList();
}
以上即為您的上課資源內容已轉為Markdown格式。若需進一步協助,歡迎告知。
來源
網頁程式設計-114學年度期中考
期中考.docx是南台科技大學-資訊管理系王派洲老師於2025/11/13所出的網頁程式設計的期中考題目,附件中有完整的程式碼原始檔案供各位同學下載。¶
本次期中考的主要題型為字串、清單、字典、變數,以下為題目解答:¶
1. 建立清單字典變數 products¶
目的¶
在 HomeController 的 Index 動作中,建立一個 List<Dictionary<string, object>> 變數 products,用來存放產品資料。
實作步驟¶
- 宣告一個
List<Dictionary<string, object>>變數。 - 每個
Dictionary包含三個鍵值對:gender(性別)、name(名稱)、pic(圖片檔名)。 - 將所有產品資料加入
products清單。
程式碼¶
var products = new List<Dictionary<string, object>>
{
new Dictionary<string, object>{{"gender",1},{"name","外套類"},{"pic","w1.jpg"}},
new Dictionary<string, object>{{"gender",1},{"name","T恤/休閒SWEAT/刷毛/BRATOP"},{"pic","w2.jpg"}},
new Dictionary<string, object>{{"gender",1},{"name","刷毛"},{"pic","w3.jpg"}},
new Dictionary<string, object>{{"gender",1},{"name","BRATOP罩杯式上衣"},{"pic","w4.jpg"}},
new Dictionary<string, object>{{"gender",2},{"name","外套類"},{"pic","m1.jpg"}},
new Dictionary<string, object>{{"gender",2},{"name","T恤/休閒SWEAT/刷毛"},{"pic","m2.jpg"}},
new Dictionary<string, object>{{"gender",2},{"name","襯衫/POLO衫"},{"pic","m3.jpg"}},
new Dictionary<string, object>{{"gender",2},{"name","針織衫/開襟外套"},{"pic","m4.jpg"}},
};
注意事項¶
gender:1 代表女性,2 代表男性。name:產品名稱。pic:對應圖片檔名。
2. 接收使用者送出的性別選項¶
目的¶
當使用者送出網頁性別選項時,Index 動作可以收到使用者送出的性別選項。
實作步驟¶
- 在
HomeController中,使用[HttpPost]屬性定義Index動作。 - 接收
int gender參數,對應表單的name="gender"。
程式碼¶
[HttpPost]
public IActionResult Index(int gender)
{
// ...
}
注意事項¶
gender參數會自動綁定到表單的name="gender"的值。- 當使用者選擇性別並按下送出,
gender參數會取得對應的值。
3. 篩選 products 變數¶
目的¶
在 Index 動作中,依據使用者選項篩選 products 變數。
實作步驟¶
- 建立
Product模型清單pds。 - 使用 LINQ 的
Where方法篩選出對應的產品。
程式碼¶
var filtered = pds.Where(p => p.Gender == gender).ToList();
注意事項¶
pds是使用Product模型建立的清單。filtered是篩選後的結果。
4. 傳遞資料至檢視頁面並顯示¶
目的¶
將篩選後的資料傳遞至 Index 檢視頁面並顯示對應產品圖片與名稱。
實作步驟¶
- 將篩選後的資料傳遞給
View。 - 在
Index.cshtml中使用@model List<Product>來接收。 - 使用
foreach迴圈顯示產品圖片與名稱。
程式碼¶
return View(filtered);
注意事項¶
- 在檢視頁面中,使用
@foreach迴圈顯示產品。
5. 定義產品類別 Product¶
目的¶
定義產品類別 Product,包含屬性 gender、name、pic。
實作步驟¶
- 建立
Product類別。 - 定義三個屬性:
Gender、Name、Pic。
程式碼¶
public class Product
{
public int Gender { get; set; }
public string Name { get; set; } = string.Empty;
public string Pic { get; set; } = string.Empty;
}
注意事項¶
Gender:性別(1 女,2 男)。Name:產品名稱。Pic:圖片檔名。
6. 建立 Product 清單物件 pds¶
目的¶
使用先前資料建立 Product 清單物件 pds。
實作步驟¶
- 將字典資料轉換為
Product清單。 - 使用
Select方法將字典轉換為Product物件。
程式碼¶
var pds = products.Select(d => new Product
{
Gender = Convert.ToInt32(d["gender"]),
Name = d["name"].ToString() ?? string.Empty,
Pic = d["pic"].ToString() ?? string.Empty
}).ToList();
注意事項¶
- 使用
Select方法將字典轉換為Product物件。
7. 使用 Product 模型進行篩選、資料傳遞與顯示¶
目的¶
使用 Product 模型進行篩選、資料傳遞與顯示。
實作步驟¶
- 篩選:
pds.Where(p => p.Gender == gender).ToList() - 傳遞:
return View(filtered) - 顯示:在
Index.cshtml中使用@foreach迴圈顯示產品。
程式碼¶
var filtered = pds.Where(p => p.Gender == gender).ToList();
return View(filtered);
注意事項¶
- 使用
Product模型可以讓程式碼更清晰、易於維護。
完整程式碼¶
HomeController.cs¶
using System.Diagnostics;
using _2025_11_13_mid_test.Models;
using Microsoft.AspNetCore.Mvc;
namespace _2025_11_13_mid_test.Controllers
{
public class HomeController : Controller
{
[HttpGet]
public IActionResult Index()
{
var products = new List<Dictionary<string, object>>
{
new Dictionary<string, object>{{"gender",1},{"name","外套類"},{"pic","w1.jpg"}},
new Dictionary<string, object>{{"gender",1},{"name","T恤/休閒SWEAT/刷毛/BRATOP"},{"pic","w2.jpg"}},
new Dictionary<string, object>{{"gender",1},{"name","刷毛"},{"pic","w3.jpg"}},
new Dictionary<string, object>{{"gender",1},{"name","BRATOP罩杯式上衣"},{"pic","w4.jpg"}},
new Dictionary<string, object>{{"gender",2},{"name","外套類"},{"pic","m1.jpg"}},
new Dictionary<string, object>{{"gender",2},{"name","T恤/休閒SWEAT/刷毛"},{"pic","m2.jpg"}},
new Dictionary<string, object>{{"gender",2},{"name","襯衫/POLO衫"},{"pic","m3.jpg"}},
new Dictionary<string, object>{{"gender",2},{"name","針織衫/開襟外套"},{"pic","m4.jpg"}},
};
var pds = products.Select(d => new Product
{
Gender = Convert.ToInt32(d["gender"]),
Name = d["name"].ToString() ?? string.Empty,
Pic = d["pic"].ToString() ?? string.Empty
}).ToList();
ViewData["SelectedGender"] = 0;
return View(pds);
}
[HttpPost]
public IActionResult Index(int gender)
{
var products = new List<Dictionary<string, object>>
{
new Dictionary<string, object>{{"gender",1},{"name","外套類"},{"pic","w1.jpg"}},
new Dictionary<string, object>{{"gender",1},{"name","T恤/休閒SWEAT/刷毛/BRATOP"},{"pic","w2.jpg"}},
new Dictionary<string, object>{{"gender",1},{"name","刷毛"},{"pic","w3.jpg"}},
new Dictionary<string, object>{{"gender",1},{"name","BRATOP罩杯式上衣"},{"pic","w4.jpg"}},
new Dictionary<string, object>{{"gender",2},{"name","外套類"},{"pic","m1.jpg"}},
new Dictionary<string, object>{{"gender",2},{"name","T恤/休閒SWEAT/刷毛"},{"pic","m2.jpg"}},
new Dictionary<string, object>{{"gender",2},{"name","襯衫/POLO衫"},{"pic","m3.jpg"}},
new Dictionary<string, object>{{"gender",2},{"name","針織衫/開襟外套"},{"pic","m4.jpg"}},
};
var pds = products.Select(d => new Product
{
Gender = Convert.ToInt32(d["gender"]),
Name = d["name"].ToString() ?? string.Empty,
Pic = d["pic"].ToString() ?? string.Empty
}).ToList();
var filtered = pds.Where(p => p.Gender == gender).ToList();
ViewData["SelectedGender"] = gender;
return View(filtered);
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
Product.cs¶
namespace _2025_11_13_mid_test.Models
{
public class Product
{
public int Gender { get; set; }
public string Name { get; set; } = string.Empty;
public string Pic { get; set; } = string.Empty;
}
}
Index.cshtml¶
@model List<_2025_11_13_mid_test.Models.Product>
@{
ViewData["Title"] = "Home Page";
var selected = ViewData["SelectedGender"] as int? ?? 0;
}
<div class="d-flex justify-content-center">
<form class="row" asp-action="Index" method="post">
<div class="col-auto">
<select class="form-select" name="gender">
<option value="0">全部</option>
@if (selected == 1)
{
<option value="1" selected>Women</option>
}
else
{
<option value="1">Women</option>
}
@if (selected == 2)
{
<option value="2" selected>Men</option>
}
else
{
<option value="2">Men</option>
}
</select>
</div>
<div class="col-auto">
<button type="submit" class="btn btn-primary col-auto">選擇</button>
</div>
</form>
</div>
<div class="border-1 m-2 row vw-100">
@if (Model != null && Model.Any())
{
foreach (var p in Model)
{
<div class="col-3 text-center mb-3">
<img src="~/images/@p.Pic" class="img-fluid" alt="@p.Name" />
<div>@p.Name</div>
</div>
}
}
else
{
<div class="col-12">沒有產品。</div>
}
</div>
以上教學與程式碼範例,完整涵蓋了題目要求的各項功能,適合用於教學或作業解說。
網頁程式設計-期中練習
設定字典變數並顯示單筆資料¶
// Index動作
public IActionResult Index()
{
Dictionary<string, dynamic> message = new Dictionary<string, dynamic> {
{"id",1 },{"pdate",DateTime.Now},{"content","資管三乙"}
};
ViewBag.message = message;
return View();
}
@{
Dictionary<string, dynamic> message = ViewBag.message as Dictionary<string, dynamic>;
}
<div class="container overflow-scroll" style="max-height:400px">
<table class="table min-vw-80">
<thead>
<tr>
<th class="w-25">日期</th>
<th class="w-50">內容</th>
<th>動作</th>
</tr>
</thead>
<tbody>
<form action="~/Home/Index" method="post">
<tr>
<!--顯示議題日期-->
<td>@message["pdate"].ToString("yy-MM-dd, HH:mm")</td>
<!--顯示議題內容-->
<td>@message["content"]</td>
<td>
<button class="btn btn-success" type="submit" name="btn" value="2">修改</button>
<button class="btn btn-danger" type="submit" name="btn" value="3">刪除</button>
</td>
</tr>
<!--設定要修改或刪除對象-->
<input type="hidden" name="" value='@message["id"]' />
</form>
</tbody>
</table>
</div>
設定包含三筆資料的字典清單並顯示¶
// Index動作
public IActionResult Index()
{
List<Dictionary<string, dynamic>> messages = new List<Dictionary<string, dynamic>>
{
new Dictionary<string, dynamic> {
{"id",1 },{"pdate",DateTime.Now},{"content","資管三甲"}
},
new Dictionary<string, dynamic> {
{"id",2 },{"pdate",DateTime.Now},{"content","資管三乙"}
},
new Dictionary<string, dynamic> {
{"id",3 },{"pdate",DateTime.Now},{"content","資管三丙"}
}
};
ViewBag.messages = messages;
return View();
}
@{
List<Dictionary<string, dynamic>> messages = ViewBag.messages as List<Dictionary<string, dynamic>>;
}
<div class="container overflow-scroll" style="max-height:400px">
<table class="table min-vw-80">
<thead>
<tr>
<th class="w-25">日期</th>
<th class="w-50">內容</th>
<th>動作</th>
</tr>
</thead>
<tbody>
@foreach (Dictionary<string, dynamic> m in messages)
{
<form action="~/Home/Index" method="post">
<tr>
<!--顯示議題日期-->
<td>@m["pdate"].ToString("yy-MM-dd, HH:mm")</td>
<!--顯示議題內容-->
<td>@m["content"]</td>
<td>
<button class="btn btn-success" type="submit" name="btn" value="2">修改</button>
<button class="btn btn-danger" type="submit" name="btn" value="3">刪除</button>
</td>
</tr>
<!--設定要修改或刪除對象-->
<input type="hidden" name="" value='@m["id"]' />
</form>
}
</tbody>
</table>
</div>
定義資料類別 Message¶
放在 Models 資料夾中的 Message.cs:
public class Message
{
public int Id { get; set; }
public DateTime Pdate { get; set; }
public string Content { get; set; }
public Message(int i, DateTime p, string c)
{
this.Id = i;
this.Pdate = p;
this.Content = c;
}
}
使用 Message 類別於 Index 動作與檢視¶
// Index動作
public IActionResult Index(int id, int btn)
{
List<Message> _messages = new List<Message>
{
new Message(1, DateTime.Now, "資管三甲"),
new Message(2, DateTime.Now, "資管三乙"),
new Message(3, DateTime.Now, "資管三丙")
};
ViewBag.messages = null; // 可依需求保留或移除
return View(_messages);
}
@model List<WebApplication1.Models.Message>
<div class="container overflow-scroll" style="max-height:400px">
<table class="table min-vw-80">
<thead>
<tr>
<th class="w-25">日期</th>
<th class="w-50">內容</th>
<th>動作</th>
</tr>
</thead>
<tbody>
@foreach (Message m in Model)
{
<form action="~/Home/Index" method="post">
<tr>
<!--顯示議題日期-->
<td>@m.Pdate.ToString("yy-MM-dd, HH:mm")</td>
<!--顯示議題內容-->
<td>@m.Content</td>
<td>
<button class="btn btn-success" type="submit" name="btn" value="2">修改</button>
<button class="btn btn-danger" type="submit" name="btn" value="3">刪除</button>
</td>
</tr>
<!--設定要修改或刪除對象-->
<input type="hidden" name="id" value='@m.Id' />
</form>
}
</tbody>
</table>
</div>
114期中考-網頁程式設計_四技資管三乙
以下是你提供程式碼及需求內容,整理成清楚的 Markdown 格式,整合包含:
- 字典變數與 List 字典定義
- 強型別類別 Message 定義
- Controller 新舊資料傳遞
- Razor Index 檢視頁面顯示
1. 定義字典變數範例¶
// 單筆字典資料
Dictionary<string, dynamic> message = new Dictionary<string, dynamic> {
{"id",1 }, {"pdate",DateTime.Now}, {"content","資管三乙"}
};
ViewBag.message = message;
return View();
2. Index檢視畫面單筆資料顯示¶
@{
Dictionary<string, dynamic> message = ViewBag.message as Dictionary<string, dynamic>;
}
<div class="container overflow-scroll" style="max-height:400px">
<table class="table min-vw-80">
<thead>
<tr>
<th class="w-25">日期</th>
<th class="w-50">內容</th>
<th>動作</th>
</tr>
</thead>
<tbody>
<form action="~/Home/Index" method="post">
<tr>
<td>@message["pdate"].ToString("yy-MM-dd, HH:mm")</td>
<td>@message["content"]</td>
<td>
<button class="btn btn-success" type="submit" name="btn" value="2">修改</button>
<button class="btn btn-danger" type="submit" name="btn" value="3">刪除</button>
</td>
</tr>
<input type="hidden" name="" value='@message["id"]' />
</form>
</tbody>
</table>
</div>
3. 包含三筆字典資料 List 定義並傳值¶
List<Dictionary<string, dynamic>> messages = new List<Dictionary<string, dynamic>>
{
new Dictionary<string, dynamic> {
{"id", 1}, {"pdate", DateTime.Now}, {"content", "資管三甲"}
},
new Dictionary<string, dynamic> {
{"id", 2}, {"pdate", DateTime.Now}, {"content", "資管三乙"}
},
new Dictionary<string, dynamic> {
{"id", 3}, {"pdate", DateTime.Now}, {"content", "資管三丙"}
}
};
ViewBag.messages = messages;
return View();
4. Index檢視畫面多筆資料顯示(List)¶
@{
List<Dictionary<string, dynamic>> messages = ViewBag.messages as List<Dictionary<string, dynamic>>;
}
<div class="container overflow-scroll" style="max-height:400px">
<table class="table min-vw-80">
<thead>
<tr>
<th class="w-25">日期</th>
<th class="w-50">內容</th>
<th>動作</th>
</tr>
</thead>
<tbody>
@foreach (Dictionary<string, dynamic> m in messages)
{
<form action="~/Home/Index" method="post">
<tr>
<td>@m["pdate"].ToString("yy-MM-dd, HH:mm")</td>
<td>@m["content"]</td>
<td>
<button class="btn btn-success" type="submit" name="btn" value="2">修改</button>
<button class="btn btn-danger" type="submit" name="btn" value="3">刪除</button>
</td>
</tr>
<input type="hidden" name="" value='@m["id"]' />
</form>
}
</tbody>
</table>
</div>
5. 定義 Message 類別(Model 資料類別)¶
public class Message
{
public int Id { get; set; }
public DateTime Pdate { get; set; }
public string Content { get; set; }
public Message(int i, DateTime p, string c)
{
this.Id = i;
this.Pdate = p;
this.Content = c;
}
}
6. Controller 同時使用 Dictionary 與 Message 物件¶
public IActionResult Index(int id, int btn)
{
Dictionary<string, dynamic> message = new Dictionary<string, dynamic> {
{"id", 1 }, {"pdate", DateTime.Now}, {"content", "資管三乙"}
};
Message _message = new Message(1, DateTime.Now, "資管三乙");
List<Dictionary<string, dynamic>> messages = new List<Dictionary<string, dynamic>>
{
new Dictionary<string, dynamic> {
{"id", 1 }, {"pdate", DateTime.Now}, {"content", "資管三甲"}
},
new Dictionary<string, dynamic> {
{"id", 2 }, {"pdate", DateTime.Now}, {"content", "資管三乙"}
},
new Dictionary<string, dynamic> {
{"id", 3 }, {"pdate", DateTime.Now}, {"content", "資管三丙"}
}
};
List<Message> _messages = new List<Message>
{
new Message(1, DateTime.Now, "資管三甲"),
new Message(2, DateTime.Now, "資管三乙"),
new Message(3, DateTime.Now, "資管三丙")
};
ViewBag.messages = messages;
return View(_messages);
}
7. Index檢視畫面,使用強型別 Model 顯示多筆 Message¶
@model List<WebApplication1.Models.Message>
<div class="container overflow-scroll" style="max-height:400px">
<table class="table min-vw-80">
<thead>
<tr>
<th class="w-25">日期</th>
<th class="w-50">內容</th>
<th>動作</th>
</tr>
</thead>
<tbody>
@foreach (Message m in Model) {
<form action="~/Home/Index" method="post">
<tr>
<td>@m.Pdate.ToString("yy-MM-dd, HH:mm")</td>
<td>@m.Content</td>
<td>
<button class="btn btn-success" type="submit" name="btn" value="2">修改</button>
<button class="btn btn-danger" type="submit" name="btn" value="3">刪除</button>
</td>
</tr>
<input type="hidden" name="id" value='@m.Id' />
</form>
}
</tbody>
</table>
</div>
這份 Markdown 內容幫你整理完整,涵蓋字典、強型別 Model、多筆資料的 Controller 與 View 表示方式,方便你直接參考與複製使用。
企業營運數位科技應用專題-期中個人報告_李健文
這個是潘惠純老師的企業營運數位科技應用專題-期中個人報告,由南台科技大學資管三乙學生李健文所製作,因為FlipClass無法上傳過大的PowerPoint檔案,因此改上傳至此。因為這個網站是我個人所製作,且跟我的專題有關,因此請老師及各位已經知道的同學不要公開。