brinch
brinch

Reputation: 2614

How to make MVC Routing handle url with dashes

I have a route defined as follows in MVC:

routes.MapRoute(
   name: "ContentNavigation",
   url: "{viewType}/{category}-{subCategory}",
   defaults: new { controller = "Home", action = "GetMenuAndContent", viewType = String.Empty, category = String.Empty, subCategory = String.Empty });

If I navigate to http://example.com/something/category-and-this-is-a-subcategory

It fills the variables as:

viewType: "something"
category: "category-and-this-is-a"
subCategory: "subcategory".

What I want is for the word before the first dash to always go into category, and the remaining into subcategory. So it would produce:

viewType: "something"
category: "category"
subCategory: "and-this-is-a-subcategory"

How can I achieve this?

Upvotes: 3

Views: 430

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038800

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"

        ...
    }
}

Upvotes: 6

Related Questions