2

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 ?

3 Answers 3

8

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 =)

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Jon... now I actually get what a ViewModel is.
This is replacing a controller right? If so, where does it go in the asp.net folder structure? In a new folder called ViewModels?
@George... this would not replace a controller, this would be used by a controller's action to populate a view, you can put it anywhere in the folder structure, I'd usually put them in a ViewModels folder.
3

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 %> -->

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.