Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning and using multiple models in MVC

I've been able to successfully return a model to a view and display the results in a strongly-typed fashion.

I have never seen an example where multiple models get returned. How do I go about that?

I suppose the controller would have something like this:

return View(lemondb.Messages.Where(p => p.user == tmp_username).ToList(), lemondb.Lemons.Where(p => p.acidity >= 2).ToList());

Does MVC let you return multiple models like that?

And then in the view I have this line at the top of the file:

@model IEnumerable<ElkDogTrader.Models.Message>

And I frequently make calls to "model" in the view.

@foreach (var item in Model)

If there were 2 models, how would I refer to them separately?

Is this possible with multiple models, or is this why people use ViewBag and ViewData?

like image 879
micahhoover Avatar asked Jun 01 '11 18:06

micahhoover


1 Answers

You can create a custom model representing the data needed for your view.

public class UserView
{
    public User User{get;set;}
    public List<Messages> Messages{get;set;}
}

And then,

return View(new UserView(){ User = user, Messages = message});

In the view:

Model.User;
Model.Messages;

The ViewBag is useful because it is dynamically typed, so you can reference members in it directly without casting. You do, however, then lose static type checking at compile time.

ViewData can be useful if you have a one-off on your view data types and know the type and will be doing a cast in the view anyway. Some people like to keep the actual typed view pure in a sense that it represents the primary model only, others like to take advantage of the type checking at compile time and therefore make custom models needed for the view.

like image 121
Matt Avatar answered Oct 01 '22 06:10

Matt