我應該爲這種情況創建一個View Model類還是應該使用 實際的Account模型類?
是的,最好創建一個代表你所需要的行動模式,你這樣做,以防止下方和上方張貼。因此,您需要處理您希望用戶使用的屬性。例如,如果你有一個有很多特性的AccountModel
,你只需要到在十分的努力上一個edit
行動的add
行動及其性能5,那麼您將創建兩個的ViewModels:
// your model or entity
public class AccountModel {
// the list of properties goes here
}
// your view models
public class CreateAccountModel {
public string Username {get;set;}
public string Password {get;set;}
public string Phone {get;set;}
}
// this model is for the scenario
// where you want users to edit their basic info
// but not the password (e.g. you have a separate
// functionality for changing the password)
public class EditAccountModel {
public string Username {get;set;}
public string Phone {get;set;}
}
現在,將您的視圖模型映射到您的實際模型或實體,您可以使用映射器工具或自行完成(累人但適用於小型模型)。以下是具體步驟:
- 您從一條信息接收模式/實體
- 您可以從數據庫中查詢你的實體
- 您從視圖模型的值複製到模型/實體
- 節省模型/實體回數據庫
確切位置在哪裏,我需要存儲視圖模型類
您可以在您創建的Models
文件夾下的MVC項目中擁有它。這實際上更像是一種偏好,沒有標準的做法 - 特別是如果你開始分層你的應用程序。把它放在一個更有意義的地方。
非常感謝您的詳細和及時的回覆!關於使用mapper工具(因爲我是一個新手,從來沒有使用過),我有一個問題:假設我的視圖模型有5個屬性,實際模型有10個,映射工具將如何解決這個問題?該工具是否會自動跳過不屬於視圖模型一部分的屬性? – 2013-04-09 06:20:16
不客氣。是的,它會跳過它,[結帳這一個](https://github.com/AutoMapper/AutoMapper)。 – 2013-04-09 06:29:36