I have a route defined as follows in MVC:
routes.MapRoute(
name: \"ContentNavigation\",
url: \"{viewType}/{category}-{subCategory}\",
defaults: new
One possibility is to write a custom route to handle the proper parsing of the route segments:
public class MyRoute : Route
{
public MyRoute()
: base(
"{viewType}/{*catchAll}",
new RouteValueDictionary(new
{
controller = "Home",
action = "GetMenuAndContent",
}),
new MvcRouteHandler()
)
{
}
public override RouteData GetRouteData(HttpContextBase httpContext)
{
var rd = base.GetRouteData(httpContext);
if (rd == null)
{
return null;
}
var catchAll = rd.Values["catchAll"] as string;
if (!string.IsNullOrEmpty(catchAll))
{
var parts = catchAll.Split(new[] { '-' }, 2, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length > 1)
{
rd.Values["category"] = parts[0];
rd.Values["subCategory"] = parts[1];
return rd;
}
}
return null;
}
}
that you will register like that:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.Add("ContentNavigation", new MyRoute());
...
}
Now assuming that the client requests /something/category-and-this-is-a-subcategory
, then the following controller action will be invoked:
public class HomeController : Controller
{
public ActionResult GetMenuAndContent(string viewType, string category, string subCategory)
{
// viewType = "something"
// category = "category"
// subCategory = "and-this-is-a-subcategory"
...
}
}