Returning and using multiple models in MVC

I managed to successfully return the model to the view and display the results in a strongly typed form.

I have never seen an example when several models return. How can I do it?

I assume the controller will 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 allow multiple models to be returned?

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

 @model IEnumerable<ElkDogTrader.Models.Message> 

And I often call the "model" in the view.

 @foreach (var item in Model) 

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

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

+8
asp.net-mvc asp.net-mvc-3 entity-framework
source share
2 answers

You can create a custom model that represents 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 view:

 Model.User; Model.Messages; 

ViewBag is useful because it is dynamically typed, so you can directly reference elements in it without casting. However, you do a static type check at compile time.

ViewData can be useful if you have one-time data types of the view and know the type, and will throw anyway. Some people like to keep the actual typed view clean, in the sense that it represents only the main model, while others prefer to use type checking at compile time and therefore create their own models for presentation.

+18
source share

I believe that ViewModel should be a way. Within the usual ViewModel, you can reference other models or define all related domain models in the view.Model model itself.

+1
source share

All Articles