不僅有意義,ViewModels是唯一應該在MVC中使用的。他們提供了許多好處,主要是靜態類型和編譯時間檢查。 ViewData和ViewBag依賴醜陋的字符串和動態屬性名稱,這些名稱很難維護且容易出錯。在asp.net MVC中,M代表ViewModel
s,而不是域模型。模型是封裝業務邏輯並被設計爲在域內工作的業務域實體。儘管使用了演示技術,模型保持不變,無論是Windows應用程序,Silverlight,ASP.NET MVC還是其他。相比之下,asp.net MVC中的ViewModels是設計用於在MVC框架中工作的類,它們繼承了控制器的特定屬性並查看特定數據,並允許域模型和控制器之間的迭代更容易。例如,在設計領域中的用戶實體時(型號)
public class User
{
public string UserName { get; set; }
public string Password { get; set; }
}
和設計登錄控制器爲您的應用程序時 - UserViewModel
public class UserViewModel
{
public string UserName { get; set; }
public string Password { get; set; }
public string ConfirmPassword { get; set; }
public string LoginHelpText { get; set; }
}
這不是現實生活中的例子,但你應該看到主設計視圖模型與設計領域模型時的差異。正如你所看到的,ViewModels是模式控制器和操作特定的,並且包含用於更好的表示和用戶迭代的數據,而域模型被設計爲在域內工作並且不關心表示 - 域模型不需要例如第二ConfirmPassword字段。爲了更好地將ViewModel與域模型一起使用,您可以查看AutoMapper和其他社區工具。
ViewModels不應包含數據庫的數據訪問邏輯,也不應包含業務邏輯。在情況下,模型也不應該包含對數據庫的訪問。爲此,您應該創建存儲庫。
public interface IUserRepository
{
int Create(User user);
bool UserAlreadyExists(string userName);
bool UpdateUserDatas(User user);
}
//than the implementation
public class UserRepository
{
// Implementation of user repository.
}
//controller
public class UserController
{
IUserRepository _userRepository;
public UserController(IUserRepository userRepository)
{
_userRepository = userRepository ?? new UserRepository();// better to write this using Dependency Injection. Search google for Ninject, StructureMap, Unity, etc
}
public ActionResult Create(UserViewModel user)
{
if (ModelState.IsValid)
{
User domainUser = new User()
{
UserName = user.UserName // etc. written for simplicity, Use Automapper instead
};
_userRepository.Create(domainUser);// create user via repository
return RedirectToAction("Index");
}
return View(user);
}
}
讀史蒂芬·桑德森的書親asp.net的MVC 3的全部細節
的可能的複製[爲什麼要使用的ViewModels?](https://stackoverflow.com/questions/14423056/why-do-we-use-viewmodels) – Liam