【发布时间】:2013-12-23 00:30:11
【问题描述】:
我正在学习 MVC,但我怀疑我是否以低效的方式编写控制器和模型。
我做了以下例子来尝试说明我的情况:
我倾向于将我的大部分逻辑放在我的模型中。一个简单的例子如下:
public partial class TestModel
{
public List<TestObject> ReportData
{
get
{
TestRepository rep = new TestRepository ();
return rep.GetData(IdObject);
}
}
public int IdObject{ get; set; }
}
一旦设置了有效的 IdObject,此模型就会生成 ReportData。这种方法的一个优点是它可以导致更小的操作方法。
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);
}
}
相对于:
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);
}
}
所以最后我通过在我的模型中保留尽可能多的逻辑来减少代码重用。 在我看来,另一个好处是我可以使大多数属性只读而忘记某些东西或有人覆盖它们(opened colsed 原则)。
我在使用这种方法时遇到的问题是,有时计算属性的成本可能很高(它们可能来自数据库或可能是处理器密集型计算),并且有时计算会进行多次。
例如,如果我的视图包含以下代码:
@if (Model.ReportData.Count() > 0)
{
foreach (var item in Model.ReportData)
{
item
}
}
如何确保数据不会反复计算?对于如何更好地编码我的模型和控制器,是否有一些建议的最佳实践?
【问题讨论】:
标签: c# asp.net-mvc asp.net-mvc-4