
| 維度 | 傳統 ASP.NET (Page Controller) | MVC 模式 |
|---|---|---|
| 代碼組織 | .aspx.cs 混合邏輯 | Model/View/Controller 分離 |
| 可測試性 | 難以單元測試 | Controller 純類,易測試 |
| HTML 控制 | 服務器控件封裝 | View 完全控制輸出 |
| URL 語義 | .aspx 物理文件 | RESTful 路由映射 |
namespace MVCTest {
public class Model {
public static int Add(int a, int b) => a + b;
public static int Add(string a, string b) => int.Parse(a) + int.Parse(b);
}
}
public class CalculatorController : Controller {
public ActionResult Add(string a, string b) {
// 1. 獲取/驗證輸入
if (!int.TryParse(a, out int x) || !int.TryParse(b, out int y))
return BadRequest("參數必須為整數");
// 2. 調用 Model 業務邏輯
int result = Model.Add(x, y);
// 3. 選擇 View 並傳遞數據
return View("Result", new { A = x, B = y, Result = result });
}
}
<%@ Page Language="C#" Inherits="ViewPage<dynamic>" %>
<h2>計算結果</h2>
<p><%: Model.A %> + <%: Model.B %> = <%: Model.Result %></p>
<a href="/calculator">返回</a>
routes.MapRoute("Calculator", "calculator/add/{a}/{b}",
new { controller = "Calculator", action = "Add" });
訪問 /calculator/add/3/5 → 自動映射到 Action 參數。