在MVC中,如何根据用于访问控制器/操作的路由返回视图。
我想在我的网站的另一部分重用控制器/操作,但我想返回一个稍微不同的视图
例如,这两个URL应该命中相同的控制器但返回不同的视图:
/管理/报告/车票
/客户/管理/报告/销售
答案 0 :(得分:0)
将控制器动作的“肉”放入另一个控制器动作调用的类中。
例如:
// /admin/reports/tickets
public class ReportsController : Controller
{
public ActionResult Tickets(int customerId)
{
using (var db = new MyDataContext())
{
var purchaseTransactions = db.Transactions
.Where(trx =>
trx.Type == 'P' // Purchase
&& trx.CustomerId == customerId)
return View(purchaseTransactions);
}
}
}
// /client/admin/report/sales
public class ReportController : Controller
{
public ActionResult Sales(int customerId)
{
using (var db = new MyDataContext())
{
var purchaseTransactions = db.Transactions
.Where(trx =>
trx.Type == 'P' // Purchase
&& trx.CustomerId == customerId)
return View(purchaseTransactions);
}
}
}
变为:
public class TicketService
{
public IEnumerable<Transaction> GetTicketPurchasesForCustomer(int customerId)
{
using (var db = new MyDataContext())
{
var purchaseTransactions = db.Transactions
.Where(trx =>
trx.Type == 'P' // Purchase
&& trx.CustomerId == customerId)
return purchaseTransactions;
}
}
}
// /admin/reports/tickets
public class ReportsController : Controller
{
public ActionResult Tickets(int customerId)
{
TicketService svc = new TicketService();
IEnumerable<Transaction> tickets = svc.GetTicketPurchasesForCustomer(customerId);
return View(tickets);
}
}
// /client/admin/report/sales
public class ReportController : Controller
{
public ActionResult Sales(int customerId)
{
TicketService svc = new TicketService();
IEnumerable<Transaction> sales = svc.GetTicketPurchasesForCustomer(customerId);
return View(sales);
}
}
答案 1 :(得分:0)
您可以为此方案配置路由,如下所示:
routes.MapRoute(
name: "tickets",
url: "admin/reports/tickets",
defaults: new { controller = "Admin", action = "Tickets" }
);
routes.MapRoute(
name: "sales",
url: "client/admin/report/sales",
defaults: new { controller = "Admin", action = "Sales" }
);
因此,每条路线导航到同一个控制器,但使用不同的操作方法,可以渲染不同的视图。
public class AdminController : Controller
{
public ActionResult Tickets() {}
public ActionResult Sales() {}
}
我建议将动作方法分开,不要试图聪明并使用相同的动作方法,然后使用一些逻辑来确定要显示的内容。它只是让事情变得混乱。