我想知道创建控制器结构的最佳方法。
假设我有几个活动,每个活动我都有几个设备。
我的想法是拥有类似的东西:
http://mydomain/event/1/device/4
所以我可以访问deviceId 4(属于eventId 1)。
我应该有两个不同的控制器吗?一个用于事件和设备或设备信息必须在EventController中?
如何在RouteConfig中使用此路由?
答案 0 :(得分:2)
完全取决于你想要如何设置它。您可以使用单独的控制器或相同的控制器。没关系。
就路由而言,如果您使用标准MVC路由,则需要为此创建自定义路由:
routes.MapRoute(
"EventDevice",
"event/{eventId}/device/{deviceId}",
new { controller = "Event", action = "Device" }
);
这与以下内容相对应:
public class EventController : Controller
{
public ActionResult Device(int eventId, int deviceId)
{
...
}
}
请确保将放在默认路线之前,以便首先捕获。有关自定义路线的详情,请参阅:http://www.asp.net/mvc/overview/older-versions-1/controllers-and-routing/creating-custom-routes-cs
或者,在MVC5 +中,您可以使用属性路由,如果您正在执行此类操作,则可以更轻松地定义自定义路由。在RouteConfig.cs
中,取消注释该行:
// routes.MapMvcAttributeRoutes();
然后,在您的行动中定义路线,如:
[Route("event/{eventId}/device/{deviceId}")]
public ActionResult Device(int eventId, int deviceId)
{
...
您还可以在控制器类上使用[RoutePrefix]
来移动部分路径以应用于整个控制器。例如:
[RoutePrefix("event")]
public class EventController : Controller
{
[Route("{eventId}/device/{deviceId}")]
public ActionResult Device(int eventId, int deviceId)
{
...
}
}
有关属性路由的详情,请参阅:http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx