2013-04-09 53 views
0

我在應用程序中有一個選項卡,單擊它後,用戶的詳細信息就會在可編輯文本框中顯示(使用佔位符HTML屬性)給他。用戶可以簡單地查看它們或可以編輯他想要的任何細節。如何將我的ViewModel映射到我的實際模型?

現在我的問題是:我應該爲這個場景創建一個View Model類還是應該使用實際的Account模型類?我想我將不得不創建一個View Model類,因爲我只需要來自Account model類的'some'屬性,但是如果我這樣做了,我將如何使其成爲'editable',然後映射編輯後的屬性(如果有)到實際的帳戶模型類?

另外,如果需要創建視圖模型類,請告訴我在哪裏存儲視圖模型類。

回答

0

我應該爲這種情況創建一個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項目中擁有它。這實際上更像是一種偏好,沒有標準的做法 - 特別是如果你開始分層你的應用程序。把它放在一個更有意義的地方。

+0

非常感謝您的詳細和及時的回覆!關於使用mapper工具(因爲我是一個新手,從來沒有使用過),我有一個問題:假設我的視圖模型有5個屬性,實際模型有10個,映射工具將如何解決這個問題?該工具是否會自動跳過不屬於視圖模型一部分的屬性? – 2013-04-09 06:20:16

+0

不客氣。是的,它會跳過它,[結帳這一個](https://github.com/AutoMapper/AutoMapper)。 – 2013-04-09 06:29:36

相關問題