具有相同行为的两个方法
本文关键字:两个 方法 | 更新日期: 2023-09-27 18:26:53
目标
创建两个具有相同行为的"不同"方法。
问题
当有人访问我的应用程序时,我希望显示一个项目列表——这个列表与myapp.com/products/offers/
提供的列表相同。换句话说,我不想在这两个方法之间重复相同的代码所以我问:我该怎么办
我现在在做什么
在HomeController
,在类型为ActionResult
的Index
方法上,存在以下代码片段:
public ActionResult Index()
{
return RedirectToAction("Offers", "Products");
}
同时在ProductsController
上,在Offers
方法上:
public ActionResult Offers()
{
var products = Products.Build.OffersList();
var categories = Categories.Build.Main();
ProductsViewModel viewModel = ProductsViewModel
{
Products = products,
Categories = categories
};
return View(viewModel);
}
现在有三件事需要考虑:
- 我的应用程序正在将客户端重定向到另一个页面,生成第二个服务器请求,浪费带宽
- 应用程序的URL从
myapp.com/
更改为myapp.com/Products/Offers/
,我真的不想这样 - 如果我重复代码,这将是多余的——更进一步地说,
ProductsController
中有一些东西根据逻辑不应该存在于HomeController
上
再说一遍:我该怎么办
将公共逻辑移动到"Service"或"Helper"类中:
class ProductListingHelper {
public ProductsViewModel GetProductsViewModel() {
var products = Products.Build.OffersList();
var categories = Categories.Build.Main();
return new ProductsViewModel() {
Products = products,
Categories = categories
};
}
}
然后,在您的两个控制器中,执行以下操作:
return View(new ProductListingHelper().GetProductsViewModel());
注意,正如Erik在评论中指出的,这将需要您创建两个视图。但是,您也可以通过将ProductListView作为其他两个视图渲染的部分视图来减少重复。
添加一个类(通常称为"服务"类),并将要重用的代码移动到该类中的方法中(可能调用方法GetProductsViewModel()
),然后从每个控制器操作中调用该方法。
希望能有所帮助。