SteveCl
SteveCl

Reputation: 4569

New to MVC | Data in a view from different sources

OK, So i have been watching some MVC vids and reading some bits. I am new to the entire MVC pattern, and until now have been happily wrapped up in the web forms world!

Like with so many demos it all seems great and I'm sure I'll have lots I dont understand as I move along, but in the first instance...

I can see that you can have a strongly typed view, which gets data from the controller. What happens if I want data in a view from different object types?? Say i want to show a grid of cars and a grid of people, which are not related in anyway??

Thx Steve

Upvotes: 1

Views: 281

Answers (4)

Scott
Scott

Reputation: 850

Instead of artificially grouping models together you could keep then separate (logically and physically) and then in the view pull the various pieces together.

Check out this post for the a great explanation of [link text][1].

[1]: http://blog.codeville.net/2008/10/14/partial-requests-in-aspnet-mvc/ partial-requests

Upvotes: 2

terjetyl
terjetyl

Reputation: 9565

Setup your strongly typed ViewData class with two properties like this

public class MyViewData 
{ 
  public IEnumerable<Car> Cars { get; set; }
  public IEnumerable<People> People { get; set; }
}

and then fill them in the controller, Sorry for the duplicate. In good MVC spirit try to use interfaces where possible to make your code more generic

Upvotes: 4

BigJoe714
BigJoe714

Reputation: 6912

What I think would be best to do in this situation would be create a class in the Models folder to hold both of these types.

Example:

public class CarsPeopleModel
    {
        public List<Car> Cars { get; set; }
        public List<Person> People { get; set; }
    }

Then your view would be:

public partial class Index : ViewPage<MvcApplication1.Models.CarsPeopleModel>
    {
    }

Upvotes: 0

CodeClimber
CodeClimber

Reputation: 4191

You can either pass both objects inside the ViewData hashtable, or create a MyViewViewModel, add two properties, and set them both from your controller.

Upvotes: 0

Related Questions