Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net Mvc - Is it acceptable for the View to call functions which may cause data retrieval?

I am currently playing around with the Asp.Net mvc framework and loving it compared to the classic asp.net way. One thing I am mooting is whether or not it is acceptable for a View to cause (indirectly) access to the database?

For example, I am using the controller to populate a custom data class with all the information I think the View needs to go about doing its job, however as I am passing objects to the view it also can cause database reads.

A quick pseudo example.

public interface IProduct
{
    /* Some Members */

    /* Some Methods */
    decimal GetDiscount();
}

public class Product : IProduct
{
    public decimal GetDiscount(){ ... /* causes database access */ }
}

If the View has access to the Product class (it gets passed an IProduct object), it can call GetDiscount() and cause database access.

I am thinking of ways to prevent this. Currently I am only coming up with multiple interface inheritance for the Product class. Instead of implementing just IProduct it would now implement IProduct and IProductView. IProductView would list the members of the class, IProduct would contain the method calls which could cause database access.

The 'View' will only know about the IProductView interface onto the class and be unable to call methods which cause data access.

I have other vague thoughts about 'locking' an object before it is passed to the view, but I can foresee huge scope for side effects with such a method.

So, My questions:

  • Are there any best practices regarding this issue?
  • How do other people using MVC stop the View being naughty and doing more to objects than they should?
like image 848
Ash Avatar asked Jan 05 '09 23:01

Ash


1 Answers

Your view isn't really causing data access. The view is simply calling the GetDiscount() method in a model interface. It's the model which is causing data access. Indeed, you could create another implementation of IProduct which wouldn't cause data access, yet there would be no change to the view.

Model objects that do lazy loading invariably cause data access when the view tries to extract data for display.

Whether it's OK is down to personal taste and preference.

However, unless you've got a good reason for lazy loading, I'd prefer to load the data into the model object and then pass that "ready-baked" for the view to display.

like image 122
Mike Scott Avatar answered Oct 15 '22 22:10

Mike Scott