3

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?

asked Apr 11, 2015 at 20:31

1 Answer 1

6

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"
 ...
 }
}
answered Apr 11, 2015 at 21:07
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.