nano nano - 3 months ago 8
ASP.NET (C#) Question

Complex routing in ASP.NET MVC5

I want to know the best approach to create my controllers structure.

Let's say I have several events and for each event I can have several devices.

My idea would be to have something like:

http://mydomain/event/1/device/4


So I can access the deviceId 4 (belonging to eventId 1).

Should I have two different controllers? One for Event and for Device or device info has to be in EventController?

How can I have this routing in my RouteConfig?

Answer

It's entirely up to you how you want to set this up. You can use separate controllers or the same controller. It doesn't matter.

As far as routing goes, if you're using standard MVC routing, you'll need to create a custom route for this:

routes.MapRoute(
    "EventDevice",
    "event/{eventId}/device/{deviceId}",
    new { controller = "Event", action = "Device" }
);

Which would correspond with something like this:

public class EventController : Controller
{
    public ActionResult Device(int eventId, int deviceId)
    {
        ...
    }
}

Just make sure you place that before the default route, so it will catch first. For more about custom routes see: http://www.asp.net/mvc/overview/older-versions-1/controllers-and-routing/creating-custom-routes-cs

Alternatively, in MVC5+ you can use attribute routing, which makes defining custom routes much easier if you're doing a lot of stuff like this. In RouteConfig.cs, uncomment the line:

// routes.MapMvcAttributeRoutes();

Then, on your action define the route like:

[Route("event/{eventId}/device/{deviceId}")]
public ActionResult Device(int eventId, int deviceId)
{
    ...

You can also use [RoutePrefix] on your controller class to move part of the route to apply to the whole controller. For example:

[RoutePrefix("event")]
public class EventController : Controller
{
    [Route("{eventId}/device/{deviceId}")]
    public ActionResult Device(int eventId, int deviceId)
    {
        ...
    }
}

For more about attribute routing see: http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx

Comments