Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does it make sense to use ViewModel

I'm trying my self in MVC3 programming. During having a look on example applications I often see things like ViewModels additional to the Models, Views and Controllers.

My question: Does it make sense to use them? If yes: How to and whats the difference between Model and ViewModel?

Thanks a lot!

Edit: Thanks for your answers:

That means if I've got a model User:

public string Username {get;set;}
public string mail{get;set;}
public string password{get;set;}
public string gender {get;set;}

And some methods like:
public int instertUserToDb()
{
...
}
public bool UserAllreadyExists()
{
...
}
public bool UpdateUserDatas()
{
...
}

The Viewmodel does not contain any connection to the Databse? And I need to Create a ViewModel: NewUser, UpdateUser, UserDetails?

Is it correct to put all the things like insert, select and so on into the Model and just use the ViewModel as like a Template for the view? Does anyone know a good example in the internet?

Thanks a lot!

like image 617
HW90 Avatar asked Dec 22 '25 23:12

HW90


1 Answers

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 ViewModels, 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

like image 128
archil Avatar answered Dec 25 '25 20:12

archil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!