I am new to .net mvc ,and here is my situation, in mvc solution, I have data modal and reposity,also have ioc container, when comes to operate data operation,should I put all my logical code in the controller?or there are any better way?
public ActionResult SomeOperate(Person person)
{
var reposity = _kernel.Get<IReposity<Person>>();
//what about if there are many database operation logical based on my generic reposity,should I put them all here?
return RedirectToAction("SomeWhere");
}
EDIT1
my generic reposity have already support basic database operations such as add,update,remove,query transaction
By default, the controller can contain business logic (and its okay). But as your application grows in size, you start doubting whether the controller should be responsible for containing the business logic.
In a more advance architecture, the Controller only acts as a "Coach" and let players do the job. In other words, the controller only worries about who should do what. Hence the name controller.
The Service Layer
The Service Layer is just a collection of classes created for one purpose, to encapsulate your business layer, moving the logic away from the controller.
See my example below for a basic implementation of a service.
Service
public class ProductService
{
private IProductRepository productRepository;
public ProductService(IProductRepository productRepository)
{
this.productRepository = productRepository;
}
public IEnumerable<Product> ListProducts()
{
return this.productRepository.ListProducts();
}
public void CreateProduct(Product productToCreate)
{
// Do validations here.
// Do database operation.
this.productRepository.Create(productToCreate);
}
}
Controller
// Controller
public class ProductController : Controller
{
private ProductService productService;
// If you are wondering how to instantiate this
// controller, see the ninject tutorial
// http://www.codeproject.com/Articles/412383/Dependency-Injection-in-asp-net-mvc4-and-webapi-us
public ProductController(ProductService productService)
{
this.productService = productService;
}
public ActionResult Index()
{
IEnumerable<Product> products = this.productService.ListProducts();
return View(products);
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(Product productToCreate)
{
if(!ModelState.IsValid)
{
return View();
}
this.productService.Create(productToCreate);
return RedirectToAction("Index");
}
The full tutorial straight from Microsoft: http://www.asp.net/mvc/tutorials/older-versions/models-(data)/validating-with-a-service-layer-cs
UPDATE
Why use a service layer
https://softwareengineering.stackexchange.com/questions/162399/how-essential-is-it-to-make-a-service-layer
Service per Model/Entity
With regards to the number of service per model, there is no absolute rule. Most of the time it can scale to one-to-one and sometimes one-to-many (referred service per module)
The number routines in a single service class depends on the number of operations in the UI, meaning if there is no delete button anywhere in the system then there shouldn't be a delete method anywhere in your code. In other words, CRUD should only apply when needed.
Service per Module
Sometimes a service can scale to multiple models, given there is an operation that requires you to updated multiple models. This is sometimes referred as "service per module", this is when a service does not represent a model but rather an operation.
RetireService
- RetireEmployee(User user)
MailingService
- SendWeeklyMails()
Services and Interfaces
Most of the time, interfaces are not required for a service layer. The only time that they are usually for the following reasons:
Large team (5 or more)
Large system
Heavy test driven development.
This link extends much on this subject:
https://softwareengineering.stackexchange.com/questions/159813/do-i-need-to-use-an-interface-when-only-one-class-will-ever-implement-it
The Single-Responsibility Principle would indicate that you should identify one responsibility for each class, and avoid putting logic into the class that doesn't pertain to that responsibility.
If this is just an exercise in learning technologies, or a small project, then you're probably safe putting most of your Entity manipulations and business logic in the individual controller actions. If this project is likely to grow, and need to be maintained by various people over time, you're probably better off defining an N-Tier architecture right off the bat.
How you do this will depend somewhat on personal preference and the nature of your project, but a popular approach is to create a "Service" or "Manager" layer where all of your business logic resides. Then the various controller actions invoke the actions on that layer, transform them into ViewModel objects, and pass them off to the views. In this architecture, Controllers end up begin very light-weight, and are focused mostly on transforming requests into service calls and composing the data that the Views will need to render.
Many people feel that the ORM (e.g. Entity Framework) represents the "data access layer," and they don't see a need to create an additional layer beyond the service layer. Other people create individualized classes to hold the queries and commands to Entity Framework, and the Service layer leverages these various other classes.
Related
I have been reading about where to put business logic in ASP.NET MVC Project and I still can't get clear on some things. Especially performing the calculations or business logic when the data is coming from UI.
I have ASP.NET MVC application using EF. The application is typical 3 tier application.
UI - has View Models
Domain (aka Service Layer) - has DTO classes
DAL - has EF entities
Each layer has its own C# classes used for transferring data between the layers.
UI has reference to Domain and Domain has reference to DAL
The business logic of the application is in Domain (service layer)
Typically any kind of business logic/calculations are done in service layer. And that is correct when the data is coming from the database.
But what if the data is coming from UI?
Lets say the view is already rendered with several fields. There is corresponding view model in UI layer. A user update some fields and click a button, which makes a ajax POST to controller action. So server now has populated view model that is coming from UI. Now i want to do some calculations and return json data.
[HttpGet]
public ActionResult Index(int id)
{
MyViewModel model = _service.GetModel(id);
return View(model);
}
[HttpPost]
public ActionResult Calculate(MyViewModel model)
{
// preform calculations but where??
var differentmodel = PerformCalculations(model);
return Json(someDifferentmodel);
}
Since Domain Layer cannot have access to View Models i can not pass MyViewModel to Domain and do the calculation there.
One option i see here like below
public ActionResult Calculate(MyViewModel model)
{
1> Convert MyViewModel to DTO
2> pass DTO to service layer for calculations
3> get calculated DTO from service layer.
4> Convert DTO to differentViewModel
return Json(differentViewModel);
}
There is lot of back & forth mapping, which seems unnecessary.
Is there any better approach?
In terms of design practice, Is it okay to introduce a new layer between UI and Domain that has reference to both UI and Domain. This new layer will be responsible to do the business logic/calculations. In-fact then i can use this layer for calculations regardless the data is coming from UI or domain. What would be this layer? (I know technically i can do that but i am asking is it recommended design practice)
You're making this unnecessarily complex. The first question to ask is: "Is this calculation logic relevant only to the view or is it applicable in other places, such as the DAL? If it's only relevant to the view, put it on your view model. If it has broader applicability then put it in a class library or something that is reference by all projects that need it. In that latter case, you'd likely just create a helper class that does the calculations, and you'd pass in only the relevant data to make those calculations.
Then, in your UI layer, you can either utilize the view model or another helper class to specifically handle the view model. For example:
Class Library
public static class CalculationHelper
{
public static int Add(int a, int b)
{
return a + b;
}
}
UI
public class MyViewModel
{
...
public FooBarSum
{
get { return CalculationsHelper.Add(Foo, Bar); }
}
}
OR
public static class UICalculationsHelper
{
public static int Add(MyViewModel model)
{
return CalculationsHelper.Add(model.Foo, model.Bar);
}
}
In OOP Design Patterns, what is the difference between the Repository Pattern and a Service Layer?
I am working on an ASP.NET MVC 3 app, and am trying to understand these design patterns, but my brain is just not getting it...yet!!
Repository Layer gives you additional level of abstraction over data access. Instead of writing
var context = new DatabaseContext();
return CreateObjectQuery<Type>().Where(t => t.ID == param).First();
to get a single item from database, you use repository interface
public interface IRepository<T>
{
IQueryable<T> List();
bool Create(T item);
bool Delete(int id);
T Get(int id);
bool SaveChanges();
}
and call Get(id). Repository layer exposes basic CRUD operations.
Service layer exposes business logic, which uses repository. Example service could look like:
public interface IUserService
{
User GetByUserName(string userName);
string GetUserNameByEmail(string email);
bool EditBasicUserData(User user);
User GetUserByID(int id);
bool DeleteUser(int id);
IQueryable<User> ListUsers();
bool ChangePassword(string userName, string newPassword);
bool SendPasswordReminder(string userName);
bool RegisterNewUser(RegisterNewUserModel model);
}
While List() method of repository returns all users, ListUsers() of IUserService could return only ones, user has access to.
In ASP.NET MVC + EF + SQL SERVER, I have this flow of communication:
Views <- Controllers -> Service layer -> Repository layer -> EF -> SQL Server
Service layer -> Repository layer -> EF This part operates on models.
Views <- Controllers -> Service layer This part operates on view models.
EDIT:
Example of flow for /Orders/ByClient/5 (we want to see order for specific client):
public class OrderController
{
private IOrderService _orderService;
public OrderController(IOrderService orderService)
{
_orderService = orderService; // injected by IOC container
}
public ActionResult ByClient(int id)
{
var model = _orderService.GetByClient(id);
return View(model);
}
}
This is interface for order service:
public interface IOrderService
{
OrdersByClientViewModel GetByClient(int id);
}
This interface returns view model:
public class OrdersByClientViewModel
{
CientViewModel Client { get; set; } //instead of ClientView, in simple project EF Client class could be used
IEnumerable<OrderViewModel> Orders { get; set; }
}
This is interface implementation. It uses model classes and repository to create view model:
public class OrderService : IOrderService
{
IRepository<Client> _clientRepository;
public OrderService(IRepository<Client> clientRepository)
{
_clientRepository = clientRepository; //injected
}
public OrdersByClientViewModel GetByClient(int id)
{
return _clientRepository.Get(id).Select(c =>
new OrdersByClientViewModel
{
Cient = new ClientViewModel { ...init with values from c...}
Orders = c.Orders.Select(o => new OrderViewModel { ...init with values from o...}
}
);
}
}
As Carnotaurus said the repository is responsible for mapping your data from the storage format to you business objects. It should handle both how to read and write data(delete, update too) from and to the storage.
The purpose of service layer on the other hand is to encapsulate business logic into a single place to promote code reuse and separations of concerns. What this typically means for me in practice when building Asp.net MVC sites is that I have this structure
[Controller] calls [Service(s)] who calls [repository(ies)]
One principle I have found useful is to keep logic to a minimum in controllers and repositories.
In controllers it is because it helps keeping me DRY. It's very common that I need to use the same filtering or logic somewhere else and if I placed it in the controller I can't reuse it.
In repositories it is because I want to be able to replace my storage(or ORM) when something better comes along. And if I have logic in the repository I need to rewrite this logic when I change the repository. If my repository only returns IQueryable and the service does the filtering on the other hand, I will only need to replace the mappings.
For example I recently replaced several of my Linq-To-Sql repositories with EF4 and those where I had stayed true to this principle could replaced in a matter of minutes. Where I had some logic it was a matter of hours instead.
The accepted answer (and upvoted hundreds of time) has a major flaw. I wanted to point this out in the comment but it will just get buried down there in 30 something comments so pointing out here.
I took over an enterprise application which was built that way and my initial reaction was WTH? ViewModels in service layer? I did not want to change the convention because years of development had gone into it so I continued with returning ViewModels. Boy it turned into a nightmare when we started using WPF. We (the team of devs) were always saying: which ViewModel? The real one (the one we wrote for the WPF) or the services one? They were written for a web application and even had IsReadOnly flag to disable edit in the UI. Major, major flaw and all because of one word: ViewModel!!
Before you make the same mistake, here are some more reasons in addition to my story above:
Returning a ViewModel from the service layer is a huge no no. That's like saying:
If you want to use these services you better be using MVVM and here is the ViewModel you need to use. Ouch!
The services are making the assumption they will be displayed in a UI somewhere. What if it is used by a non UI application such as web services or windows services?
That is not even a real ViewModel. A real ViewModel has observability, commands etc. That is just a POCO with a bad name. (See my story above for why names matter.)
The consuming application better be a presentation layer (ViewModels are used by this layer) and it better understand C#. Another Ouch!
Please, don't do that!
Repository layer is implemented to access the database and helps to extend the CRUD operations on the database. Whereas a service layer consists of the business logic of the application and may use the repository layer to implement certain logic involving the database. In an application, it is better to have a separate repository layer and service layer. Having separate repository and service layers make the code more modular and decouple the database from business logic.
Usually a repository is used as scaffolding to populate your entities - a service layer would go out and source a request. It is likely that you would put a repository under your service layer.
I've made a custom model, and I want to mock it. I'm fairly new to MVC, and very new to unit testing. Most approaches I've seen create an interface for the class and then make a mock that implements the same interface. However I can't seem to get this to work when actually passing the interface into the View. Cue "simplified" example:
Model-
public interface IContact
{
void SendEmail(NameValueCollection httpRequestVars);
}
public abstract class Contact : IContact
{
//some shared properties...
public string Name { get; set; }
public void SendEmail(NameValueCollection httpRequestVars = null)
{
//construct email...
}
}
public class Enquiry : Contact
{
//some extra properties...
}
View-
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<project.Models.IContact>" %>
<!-- other html... -->
<td><%= Html.TextBoxFor(model => ((Enquiry)model).Name)%></td>
Controller-
[HttpPost]
public ActionResult Index(IContact enquiry)
{
if (!ModelState.IsValid)
return View(enquiry);
enquiry.SendEmail(Request.ServerVariables);
return View("Sent", enquiry);
}
Unit Testing-
[Test]
public void Index_HttpPostInvalidModel_ReturnsDefaultView()
{
Enquiry enquiry = new Enquiry();
_controller.ModelState.AddModelError("", "dummy value");
ViewResult result = (ViewResult)_controller.Index(enquiry);
Assert.IsNullOrEmpty(result.ViewName);
}
[Test]
public void Index_HttpPostValidModel_CallsSendEmail()
{
MockContact mock = new MockContact();
ViewResult result = (ViewResult)_controller.Index(mock);
Assert.IsTrue(mock.EmailSent);
}
public class MockContact : IContact
{
public bool EmailSent = false;
void SendEmail(NameValueCollection httpRequestVars)
{
EmailSent = true;
}
}
Upon a HttpPost I get a "Cannot create an instance of an interface" exception. I seems that I can't have my cake (passing a model) and eat it (pass mock for unit testing). Maybe there's a better approach to unit testing models bound to views?
thanks,
Med
I'm going to throw it out there, if you need to mock your models you're doing it wrong. Your models should be dumb property bags.
There is absolutely no reason that your model should have a SendEmail method. That is functionality that should be invoked from a controller calling to an EmailService.
Responding to your question:
After years of working with Separation of Concern (SOC) patterns like MVC, MVP, MVVM and seeing articles from people brighter than me (I wish I could find the one I'm thinking off about this but maybe I read it in a magazine). You will eventually conclude in an enterprise application you will end up with 3 distinct sets of model objects.
Previously I was a very big fan of doing Domain Driven Design (DDD) using a single set of business entities that were both plain old c# objects (POCO) and Persistent Ignorant (PI). Having domain models that are POCO/PI leaves you with a clean slate of objects where there is no code related to accessing the object storage or having other attributes that have schematic meaning for only 1 area of the code.
While this works, and can work fairly well for a period of time, there is eventually a tipping point where the complexity of expressing the relationship between View, Domain Model, and Physical Storage Model becomes too complex to express correctly with 1 set of entities.
To solve the impedance mismatches of View, Domain and Storage you really need 3 sets of models. Your ViewModels will exactly match your views binding to facilitate it to be easy to work with the UI. So this will frequently have things such as adding a List to populate drop downs with values that are valid for your edit view/action.
In the middle is the Domain Entities, these are the entities that you should validate against your business rules. So you will map to/from them on both sides to/from the view and to/from the storage layer. In these entities is where you could attach your code to do validation. I personally am not a fan of using attributes and coupling validation logic into your domain entities. It does make alot of sense to couple validation attributes into your ViewModels to take advantage of the built in MVC client side validation functionality.
For validation I would recommend using a library like FluentValidation (or your own custom one, they're not hard to write) that lets you separate your business rules from your objects. Although with new features with MVC3 you can do remote validation severside and have it display client side, this is an option to handle true business validation.
Finally you have your storage models. As I said previously I was very zealous on having PI objects being able to be reused through all layers so depending on how you setup your durable storage you might be able to directly use your domain objects. But if you take advantage of tools like Linq2Sql, EntityFramework (EF) etc you will most likely have auto generated models with code for interacting with the data provider so you will want to map your domain objects to your persistence objects.
So wrap all of this up this would be a standard logic flow in MVC actions
User goes to edit product page
EF queries the database to get the existing product information, inside the repository layer the EF data objects are mapped to the Business Entities (BE) so all the data layer methods return BEs and have no external coupling to the EF data objects. (So if you ever change your data provider you don't have to alter a single line of code except for the internal implementation)
The controller gets the Product BE and maps it to a Product ViewModel (VM) and adds collections for the different options that can be set for drop down lists
Return View(theview, ProductVM)
User edits the product and submits the form
Client side validation is passed (useful for date validation / number validation instead of having to submit the form for feedback)
The ProductVM gets mapped back to ProductBE at this point you would validate the business rules along the lines ValidationFactory.Validate(ProductBE), if it's invalid return messages back to view and cancel edit, otherwise continue
You pass the ProductBE into your repository model, inside the internal implementation of the data layer you map the ProductBE to the Product Data Entity for EF and update the database.
2016 edit: removed usages of Interface as separation of concerns and interfaces are entirely orthogonal.
Your issue is here:
public ActionResult Index(IContact enquiry)
MVC in the background has to create a concrete type to pass to the method when calling it. In this method's case, MVC needs to create a type which implements IContract.
Which type? I dunno. Neither does MVC.
Instead of using interfaces in order to be able to mock your models, use normal classes that have protected methods which you can override in mocks.
public class Contact
{
//some shared properties...
public string Name { get; set; }
public virtual void SendEmail(NameValueCollection httpRequestVars = null)
{
//construct email...
}
}
public class MockContact
{
//some shared properties...
public string Name { get; set; }
public bool EmailSent {get;private set;}
public override void SendEmail(NameValueCollection vars = null)
{
EmailSent = true;
}
}
and
public ActionResult Index(Contact enquiry)
It is possible to use interfaces.
See: http://mvcunity.codeplex.com/
I'm developing an application using asp.net mvc, NHibernate and DDD. I have a service layer that are used by controllers of my application. Everything are using Unity to inject dependencies (ISessionFactory in repositories, repositories in services and services in controllers) and works fine.
But, it's very common I need a method in service to get only object in my repository, like this (in service class):
public class ProductService {
private readonly IUnitOfWork _uow;
private readonly IProductRepository _productRepository;
public ProductService(IUnitOfWork unitOfWork, IProductRepository productRepository) {
this._uow = unitOfWork;
this._productRepository = productRepository;
}
/* this method should be exists in DDD ??? It's very common */
public Domain.Product Get(long key) {
return _productRepository.Get(key);
}
/* other common method... is correct by DDD ? */
public bool Delete(long key) {
usign (var tx = _uow.BeginTransaction()) {
try
{
_productRepository.Delete(key);
tx.Commit();
return true;
} catch {
tx.RollBack();
return false;
}
}
}
/* ... others methods ... */
}
This code is correct by DDD ? For each Service class I have a Repository, and for each service class need I do a method "Get" for an entity ?
Thanks guys
Cheers
Your ProductService doesn't look like it followed Domain-Driven Design principles. If I understand it correctly, it is a part of Application layer between Presentation and Domain. If so, the methods on ProductService should have business meaning with regard to products.
Let's talk about deleting products. Is it as simple as executing delete on the database (NHibernate, or whatever?) I think it is not. What about orders which reference the to-be-deleted product? And so on and so forth. Btw, Udi Dahan wrote a great article on deleting entities.
Bottom line is, if your application is so simple that services do really replicate your repositories and contain only CRUD operations, you probably shouldn't do DDD, throw away your repositories and let services operate on entities (which would be simple data containers in that case).
On the other hand, if there is a complicated behavior (like the one with handling 'deleted' products), there is a point in going DDD path and I strongly advocate doing so.
PS. Despite which approach (DDD or not) you will eventually take I would encourage you to use some Aspect Oriented Programming to handle transaction and exception related stuff. You would end up with way to many methods such as DeleteProduct with same TX and exception handling code.
That looks correct from my perspective. I really didn't like repeating service and repository method names over and over in my asp.net MVC project, so I went for a generic repository approach/pattern. This means that I really only need one or two Get() methods in my repository to retrieve my objects. This is possible for me because I am using Entity Framework and I just have my repository's get() method return a IQueryable. Then I can just do the following:
Product product = from p in _productRepository.Get() where p.Id == Id select p;
You can probably replicate this in NHibernate with linq -> NHibernate.
Edit: This works for DDD because this still allows me to interchange my DAL/repositories as long as the data library I am using (Nhibernate, EF, etc..) supports IQueryable.
I am not sure how to do a generic repository without IQueryable, but you might be able to use delegates/lambda functions to incorporate it.
Edit2: And just in case I didn't answer your question correctly, if you are asking if you are supposed to call your repository's Get() method from the service then yes, that is the correct DDD design as well. The reason is that the service layer is supposed to handle all your business logic, so it decides exactly how and what data to retrieve (for example, do you want it in alphabetical order, unordered, etc...). It also means that it can perform validation after loading if needed or validation before deleting and/or saving.
This means that the service layer doesn't care exactly how that data is stored and retrieved, it only decides what data is stored and retrieved. It then calls on the repository to handle the request correctly and retrieve/store the data in the way the service layer tells it to. Thus you have correct separation of concerns.
In the MVC model, where does the responsibility of loading the view model lie?
Should the Controller load the data?
Should the View Model itself load the data ala:
MyViewModel viewModel = MyViewModel.Create(someValue);
Should a Service Layer load it ala:
MyViewModel viewModel = MembershipService.Instance.Load(someValue);
See this example of the really clean technique:
http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/06/29/how-we-do-mvc-view-models.aspx
Alternatively you can do it manually: see "ASP.NET MVC In Action" book or CodeCampServer sources for examples. Basically you inject IViewModelMapper { public ViewModel Map(data); } to the controller. The neat thing is that it makes your IoC automatically pass services and repositories to your ViewModel mapper. However this can really make controllers be bloated with mapper interfaces so something like Jimmy Bogard's technique, even without AutoMapper, but with action filters than do pick IViewModelMapper, would be better.
If you can't do this, then I'd suggest stick with ViewModel handling mapping as Mathias suggested.
UPDATE: here's an example of automapper-like configuration with bits of CodeCampServer way. Not sure if it will work as is (or useful at all), just a demonstration.
public abstract class ViewModelMapper<Source, ViewModel> where Source: class, ViewModel: IViewModel
{
public abstract ViewModel Map(Source source);
}
public class ProductDetailsViewModel
{
public ProductViewModel Product { get; set; }
punlic IList<Language> AvailableProductLanguages { get; set; }
}
public class ProductDetailsViewMapper: ViewModelMapper<Product, ProductDetailsViewModel>
{
private ILanguageRepository languages;
public ProductDetailsViewMapper(ILanguageRepository languages)
{
this.languages = languages;
}
public override ProductDetailsViewModel Map(Product source)
{
var vm = new ProductDetailsViewModel();
AutoMapper.Map<Product, ProductDetailsViewModel>(product, vm);
vm.AvailableProductLanguages = languages.GetAppropriateFor(product);
}
}
public class ViewModelMapperActionFilter: ActionFilter
{
Type mapperType;
public ViewModelMapperActionFilter()
{
}
public ViewModelMapperActionFilter(Type mapperType)
{
}
public void OnActionExecuted(ControllerContext context)
{
var model = context.Result.ViewData.Model;
var mapperType = this.MapperType ?? this.GetMapperTypeFromContext(context);
// this is where magic happens - IoC grabs all required dependencies
var mapper = ServiceLocator.GetInstance(mapperType);
var method = mapperType.GetMethod("Map");
Check.Assert(method.GetArguments()[0].ArgumentType == model.GetType());
context.Result.ViewData.Model = method.Invoke(mapper, new[]{model});
}
}
public class ProductsController: Controller
{
[ViewModelMapper(typeof(ProductDetailsViewMapper))]
// alternatively [ViewModelMapper()] will auto-pick mapper name by controller/action
public ActionResult Details(EntityViewModel<Product> product)
{
// EntityViewModel is a special type, see
// http://stackoverflow.com/questions/1453641/my-custom-asp-net-mvc-entity-binding-is-it-a-good-solution
return View(product.Instance);
}
}
//Global.asax.cs:
IoC.Register(AllTypes.DerivedFrom(typeof(ViewModelMapper<>)));
The controller is the glue that binds the model and view together. You want both your model classes and views to have as few dependencies as possible on the other layers of your app. Therefore, the controller should always load data for the view, regardless of where the data comes from, or what design patterns you use in your model for retrieving it.
You may have a bunch of layers of abstraction for your data loading operations within your model layer, but the controller should be calling some method, or methods, which at some point down the call chain, goes to whatever persistent datastore you are using and gets the data needed for your view.
The controller should be providing all of the objects that the view needs, as this is really one of its key responsibilities. Whether that means using the appropriate model object to grab the data from a database, or initializing a "view model" class to wrap all the objects and properties needed for the view to display, it doesn't matter.
Personally, I have always used Linq-to-SQL in conjunction with ASP.Net MVC, and have had great success using repository classes that grab the necessary objects from the data context. To allow my controllers to be unit tested, I use a dependency injection framework (StructureMap in my case) to have ASP.Net MVC provide my controller with a default instance of my repository interface.
the controller should never load data. that should be in either the model or in a data layer.
my preference is in a data layer so i can seperate it from the model which i think isa there only to store/represent data that is given to the controller and then the view.
i implement the repository pattern for data retrieval
I like to have the ViewModel load the data.
ViewModels are accessible from all Controllers. That way its possible to avoid code dupplication.
See this sample ASP.NET MVC - Job of Controllers
I layer things this way:
view->controller->service->persistence
Requests flow from front to back; responses go from back to front.
The persistence layer worries about the database; it makes model data available. It knows nothing about any of the other layers.
The service layer's methods map to use cases. It knows about the persistence layer, units of work and transactions. It validates its inputs, acquires database connections, makes them available to the persistence layer, cleans up resources, and works with model objects to fulfill the use cases. It can be exposed as a web service or EJB if needed.
The controller and view go together. It knows about the service layer. It maps requests to services, binds and validates incoming request parameters, passes them to the service layer, and routes responses to the appropriate view.
The view only worries about displaying the data that the controller provides for it. It knows about the controller.
So it's the service that deals with the database. Controller and view collaborate to display info, nothing more.