I am learning MVC and have doubts on if I am coding my controllers and models in an inefficient way.
I have made the following examples to try and illustrate my case:
I tend to put most of my logic in my models. a simple example of this would be the following:
public partial class TestModel
{
public List<TestObject> ReportData
{
get
{
TestRepository rep = new TestRepository ();
return rep.GetData(IdObject);
}
}
public int IdObject{ get; set; }
}
this model generates the ReportData as soon as a valid IdObject is set. an advantage of this approach is that it can lead to smaller action methods.
public class TestController
{
public ActionResult Test1()
{
return View(new TestModel());
}
[HttpGet]
public ActionResult Test2()
{
return View(new TestModel());
}
[HttpPost]
public ActionResult Test3(TestModel model)
{
return View(model);
}
}
as opposed to :
public class TestController
{
public ActionResult Test1()
{
TestModel model = new TestModel();
TestRepository rep = new TestRepository ();
model.ReportData = rep.GetData(IdObject);
return View(model);
}
[HttpGet]
public ActionResult Test2()
{
TestModel model = new TestModel();
TestRepository rep = new TestRepository ();
model.ReportData = rep.GetData(IdObject);
return View(model);
}
[HttpPost]
public ActionResult Test3(TestModel model)
{
TestRepository rep = new TestRepository ();
model.ReportData = rep.GetData(IdObject);
return View(model);
}
}
so in the end I cut down on code reuse by sticking as much logic as possible in my model. An other upside in my eyes is that i can make most properties read only and forget about something or someone overwriting them (opened colsed principle).
the problem I am having with this approach is that sometimes properties can be costly to calculate (they may come from databases or might be processor intensive calculations) and there are times where the calculation is done multiple times.
for example if I have a view that includes the following code:
@if (Model.ReportData.Count() > 0)
{
foreach (var item in Model.ReportData)
{
item
}
}
how can I make sure that the data is not calculated over and over again? and is there a best practice of some advice o how to better code my models and controllers?