tags:

views:

275

answers:

2

I am working on an ASP.NET MVC project were I am using routing to produce friendly URLs and have an issue I am not sure how best to solve.

The routing I have setup work like the following

{category}

{category}/{manufacturer}

{category}/{manufacturer}/{product}

The problem I have is that I want to display matches to the same route in differing ways. e.g.

Category1 Displays

  • A Description followed by
  • An Image followed by a
  • List of Products

Category2 Displays

  • An Image followed by
  • Promotions followed by a
  • Description

I have got round this by having an enum ViewTemplate associated with the category and then return the view with the same name, but this doesn't feel right, firstly because I'm not sure I should be logic like this in the controller action and also I am still making the same database calls which is fine for some stuff but if a category has 500 products I am still pulling them out the database even for the Category2 when they won't be used. Now to the point:

  1. Is return different views from the same controller action wrong?
  2. How would you deal with loading different data for each view?
  3. If I am wrong (which I think I am) How should I be doing something like this?

Thanks for any help you could be.

+6  A: 

I'm not a guru here, but in other MVC frameworks, I've done (and seen) similar things. It's the Controller's job to determine which View is returned based on who's asking, what's asked, etc. How you determine the View name is really a matter of what's best for your application and/or its modifiability/testability.

Harper Shelby
+3  A: 

in MVC it is the controllers responsibility to decide which view to return, and so it is perfectly normal to have a controller that returns a number of different views. Controllers should be relatively simple. They should take an instruction from the client. Access the model to kick off any changes that need making. Get some data from the model. And use this data to decide which view to show to the client.

In your situation I think that the appropriate thing for the controller to do is this:

  1. Get some general information about the product.
  2. Use this general information to decide which view to use.
  3. Get the data for that particular view.
  4. Return the view.

I think that if you are worried that you are doing wrong you need to make sure that the model only contains methods that make sense in the context of the domain. They shouldn't be too closely bound up with a particular view. for example Product.GetDataForMiniProductView(int id) is wrong, This should be controller logic. on the other hand Product.GetStockCount should definitely be in the model and not the controller.

Jack Ryan