Tony Martinez Tony Martinez - 1 year ago 73
C# Question

ASP.NET MVC 4 How to pass multiple objects through the same controller to a view?

In my ASP.NET MVC4 Web Application I'm trying to display a table with some information from a SQL database using Entity Framework. Generating a view from the SQL table(using database firs with EF) was easy for me to do, but now I'm stuck on a more conceptual question. Right now my controller passes the list of entity objects to my view.

public ActionResult Index()
return View(db.APU_daily_summary_test.ToList());

But now I need to calculate the min and max of some of these columns in SQL. I know that I should calculate the min and max inside the model, but after that I don't know how I should pass this information through the controller to the view. Do I need a view model? An API? An extra controller?

Answer Source

You just described a perfect use case for a View Model.

Here's the structure I would recommend:

public class MyViewModel
    public int MaxOfColumn { get; set; }
    public List<InnerViewModel> Items { get; set; }

public class InnerViewModel
    // Create properties here which represent the Model's columns you need to display

Not only does a view model help break it up so you don't have to do many data operations within your view. This also breaks a very common bug with more complex models where the EF object has a circular reference.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download