0

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?

Tony Martinez
  • 335
  • 3
  • 16
  • Why not use aggregate Linq functions on your view to find the max of those columns? `mylist.Max(m => m.Column)`? You could also have a method in your view model that does that for you, if you would prefer to keep it separate. It's such an easy one liner though, I'd personally just put it in the view. – Justin Loveless Nov 10 '16 at 19:29
  • Awesome thank you, that's what I was trying to figure out how to do until I realized there was probably another way to do it with a view model. – Tony Martinez Nov 10 '16 at 20:41

2 Answers2

0

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.

Community
  • 1
  • 1
willwolfram18
  • 1,747
  • 13
  • 25
0

You could use a view model..

public class MyViewModel
{
    public List<MyType> MyList { get; set; }
    public int MaxVal { get; set; }
    public int MinVal { get; set; }
}

... and associate your view with the model...

or simply call the aggregated LINQ functions Max and Min from your view:

 {@ int max = Model.Max(x => x.MyColumn); }
Nikkster
  • 327
  • 2
  • 13