初識MVC框架 Model與ViewModel

2021-10-04 04:10:04 字數 3090 閱讀 7775

model:領域模型,與資料庫建模一一對應。viewmodel:使用者檢視模型,與view層使用者操作直接關聯。本文以軟體開發平台中客戶(customer)為例進行說明。

乙個簡單的model

web開發框架中mvc架構,本來就只有乙個model的,這個model在領域驅動開發中主要擔任領域模型的角色,和業務邏輯緊密關聯的,直接與資料庫表進行對映的

/// 

/// 物料

///

public

partial

class

inventory

///

/// 物料編碼

///

[required

]public

string code

///

/// 是否啟用

///

public

bool isenabled

///

/// 建立時間

///

public datetime? createat

///

/// 建立人

///

public

string createby

///

/// 修改時間

///

public datetime? modifyat

///

/// 修改人

///

public

string modifyby

///

/// 從屬於哪個系列id

///

public

int? serialid

///

/// 系列模型

///

public

inventoryserial inventoryserial

///

/// 系列名稱。

///

public

string serialname

}}

模型裡面有乙個自增長的inventoryid,包含物料編號code及屬於哪個系列等屬性,這些在資料庫中物料表都有對應的字段,通過entityframework進行模型對映。

乙個簡單的viewmodel

但是在比較複雜的業務場景中,乙個領域模型已經不能滿足於開發這一場景,已經需要借助第二個模型,我們姑且叫做使用者模型,即與使用者直接打交道的檢視模型(viewmodel)

/// 

/// 物料

///

public

partial

class

inventory

///

/// 物料編碼

///

[required

]public

string code

///

/// 是否啟用

///

public

bool isenabled

///

/// 建立時間

///

public datetime? createat

///

/// 建立人

///

public

string createby

///

/// 修改時間

///

public datetime? modifyat

///

/// 修改人

///

public

string modifyby

///

/// 從屬於哪個系列id

///

public

int? serialid

///

/// 系列模型

///

public

inventoryserial inventoryserial

///

/// 系列名稱。

///

public

string serialname

}}

viewmodel顧名思義是應用於view層的(這和mvvm原理同,當然我們也可以在view層直接使用mvvm架構,這個不是我們討論的範圍,有興趣的夥伴可以檢視angularjs相關知識。),在controller層(或服務層)將model轉化為viewmodel後,再reponse給view層進行資料繫結。

model與viewmodel關聯

直接寫**轉化:

//customer customer 已經有值的物件

customerviewmodel customerviewmodel =

newcustomerviewmodel

{///

/// id,檢視中隱藏屬性

///

customerid=customer.customerid,

///

/// 客戶編碼

///

code=customer.code,

///

/// 客戶名稱

///

name =customer.name ,

///

/// 客戶位址1

///

address1 =customer.address1,

///

/// 客戶位址2

///

address2 =customer.address2;

///

/// 客戶位址3

///

address3 =customer.address3 ,

///

/// 所在城市

///

city =customer.

city

customerviewmodel customerviewmodel=customer.

tomodel()

;

初識MVC框架

什麼是mvc?剛開始聽到mvc這個詞的時候,對其茫無所知,通過近期的學習,對其有所了解。mvc全名是model view controller,是模型 model 檢視 view 控制器 controller 的縮寫,一種軟體設計典範,用一種業務邏輯 資料 介面顯示分離的方法組織 將業務邏輯聚集到乙...

初識 框架與架構

系統 的維基百科定義 系統泛指由一群有關聯的個體組成,根據某種規則運作,能完成個別元件不能單獨完成的工作的群體。它的意思是 總體 整體 或 聯盟 子系統 的維基百科定義 子系統也是由一群有關聯的個體所組成的系統,多半會是更大系統中的一部分。子系統的定義和系統定義是一樣的,只是觀察的角度有差異,乙個系...

MVC框架與MVT框架詳解(更新完善中 )

mvc 高可擴充套件性 向後相容 後面的版本都可以相容 低耦合 模組與模組之間不要有太強的依耐性 高內聚 指乙個軟體模組是由相關性很強的 組成,只負責一項任務,也就是常說的單一責任原則。專案的入口 manage.py 專案的配置 test1 專案的開發 自定義應用 mvc原理圖如下 mvt原理圖如下...