I am looking to use asp.net MVC for new project. I looked at different examples at asp.net and over web. I still didn't get answer to , what is the best way to combine output of different models into a single view. For example my home page will contain catgories, locations, snapshots of recent posts. These will come from three different models. Do I create single viewdata with everything in it and messup within view to place content accordingly ?
I usually create one view model class that aggregates multiple data model classes in this scenario.
I believe view and data should be two different set of objects because sometimes you need to do data trasformations (e.g. formating a decimal from a data model class to a string in currency format in view model) in the controller class before it is sent to the view.
You create a ViewModel for your homepage... something like...
public class MyHomepageViewModel
{
public Categories MyCategories { get; set; }
public Locations MyLocations { get; set; }
public Snapshots MySnapshots { get; set; }
public MyHomepageViewModel(Categories categories, Locations locations, Snapshots snapshots)
{
MyCategories = categories;
MyLocations = locations;
MySnapshots = snapshots;
}
}
and then you strongly type your homepage to this view model and you will have access to everything that you need in your view =)
You need View Model for this:
public class HomeViewModel {
public IList<Category> Categories;
public IList<Location> Locations;
public IList<Snapshot> Snapshots;
public IList<Post> Recent;
}
Your View must be strongly-typed:
<%@ Page Inherits="System.Web.Mvc.ViewPage<HomeViewModel>" %>
<!-- <% var categories = Model.Categories %> -->
Let me just ask quickly if i understand this correctly since I'm facing the same question myself:
If for example I want to create a view which let's say is used to create a new product and for that product I want to specify a category and a supplier via a drop down list with all suppliers and another one with all categories. If this is my scenario I have to make a special model which is basically a group of my 3 existing models (Product, Category, Supplier) and then use this model to generate a view?
Am I correct? Is this the only way because frankly this seems quite messy to me as there could be quite a few of these kinds of situations where different objects from database are displayed on page simultaneosly. That means that besides standard models based on their DB counterparts (in my case Product, Supplier, Category) I have a whole new set of models related specifically to each "special case" view I want to have? (such as AddModifyProduct, etc.)
Is this really the best solution available?