I have a problem and don’t know where to start as I am new to MVC. I have three tables:
- User (UserID, Username, etc…) This defines users.
- Service (ServiceID, ServiceName, etc…) This defines services.
- Licenses (ID, UserID, ServiceID, etc…) Maps services to a user.
In the back-end the user can access a service if he has a license. Ideally I would like a list of services in my EditUser view where I could check which services they should have licenses to.
This list needs to pre-populate with current licenses and if one is unchecked and saved it needs to be deleted.
I have all the methods to add and remove licenses, but I need to know how to implement this in my controller and view.
Thanks in advance.
First of all, define a ViewModel
A View Model is simply a helper class that contains everything that you’ll need to display a view. Then, in your action:
Then, make your view a typed view with EditUserViewModel for model:
You can reuse the EditUserViewModel class for other views, UserDetails, for instance. In that case you might want to rename and get rid of the “Edit” prefix.
UPDATE to clarify question in comments:
Rule of thumb: Keep your view models small, dumb and simple. No methods, functionality or intelligence, just a couple of properties that assist you in the display process. You’ll only want to reuse View Models on views that are very similar, like would be the case with an
EditUserandDisplayUserview. You’d have a different view model for aDisplayServicesview, etc.