user123941
user123941

Reputation: 21

Combining Multiple outputs in single view in asp.net MVC

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 ?

Upvotes: 2

Views: 1182

Answers (3)

eu-ge-ne
eu-ge-ne

Reputation: 28153

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

Upvotes: 3

Jon Erickson
Jon Erickson

Reputation: 114886

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

Upvotes: 8

oscarkuo
oscarkuo

Reputation: 10453

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.

Upvotes: 0

Related Questions