首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

MVC 模式在 ASP.NET 中的應用:從傳統三層到職責分離

     編輯:關於ASP.NET

架構演進對比

MVC 架構圖

維度傳統 ASP.NET (Page Controller)MVC 模式
代碼組織.aspx.cs 混合邏輯Model/View/Controller 分離
可測試性難以單元測試Controller 純類,易測試
HTML 控制服務器控件封裝View 完全控制輸出
URL 語義.aspx 物理文件RESTful 路由映射

極簡 Model 示例

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);
    }
}

Controller 協調流程

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 });
    }
}

View 純渲染

<%@ 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 參數。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved