首先,定義一個視圖模型
public class EditUserViewModel
{
public User User { get; set; }
public IList<License> Licenses { get; set; }
public IList<Service> Services { get; set; }
}
視圖模型很簡單,包含了你需要顯示視圖一切輔助類。然後,在你的行動:
public ActionResult EditUser(int id)
{
var userViewModel = new EditUserViewModel
{
User = // Get user from db
Licenses = // Get licenses for that user
Services = // Getservies the user in entitled to
}
return View(userViewModel);
}
然後,讓你的看法與EditUserViewModel類型化視圖模式:
@model EditUserViewModel
@* //Some html or whatever here *@
@* //Access your model properties as follows *@
@Model.User
@Model.Licenses
@Model.Service
可以重用EditUserViewModel類其他意見,是UserDetails,例如。在這種情況下,您可能需要重命名並刪除「編輯」前綴。
更新,以澄清問題的意見: 經驗法則:保持您的視圖模型小,愚蠢和簡單。沒有方法,功能或智能,只有一些幫助您進行顯示過程的屬性。您只希望在視圖非常相似的情況下重用視圖模型,例如EditUser
和DisplayUser
視圖。你會有一個不同的視圖模型爲DisplayServices
視圖等。
謝謝。這很有幫助。觀看模型是前進的方向。擁有一個包含所有內容的單一視圖模型或每個不同視圖的許多特定視圖模型會更好嗎? – TheGwa 2011-03-17 09:01:57
@TheGwa - 不客氣。您最終可能會擁有多個視圖模型,因爲對於EditUser視圖而言,wat不太可能適合EditServices視圖。經驗法則:保持他們小,笨,簡單。沒有方法,功能或智能,只有一些幫助您進行顯示過程的屬性。 – 2011-03-17 09:13:29