Not only it makes sense, ViewModels are the only ones that SHOULD be used in MVC. They give number of benefits, and main of them are static typing and compile time checking. ViewData and ViewBag rely on ugly strings and dynamic property names, which are hard to maintain and error prone. In asp.net MVC, M stands for ViewModel
s, not the domain models. Models are business, domain entities that encapsulate business logic and are designed to work within domain. Models stay the same despite the presentation technology used, be it Windows application, Silverlight, ASP.NET MVC or others. By contrast, ViewModels in asp.net MVC are the classes designed to work within MVC framework, they carry on controller specific and view specific data and allow easier iteraction between domain Models and Controller. For example, when designing User entity within domain (Model)
public class User
{
public string UserName { get; set; }
public string Password { get; set; }
}
and when designing login controller for your application - UserViewModel
public class UserViewModel
{
public string UserName { get; set; }
public string Password { get; set; }
public string ConfirmPassword { get; set; }
public string LoginHelpText { get; set; }
}
this is not the real life example, but you should see the main difference when designing view models vs designing domain models. As you see, ViewModels are mode controller and action specific, and contain data for better presentation and user iteraction, whereas domain models are designed to work within domain and do not care about presentation - domain models do not ever need the second ConfirmPassword field for example. To better use ViewModels with domain models, you could take a look at AutoMapper and other community tools.
ViewModels should not contain data access logic for database, neither business logic. In case, Models also should not contain access to database. For that purpose, you should create repositories.
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);
}
}
Read steven sanderson's book pro asp.net mvc 3 for full details