ASP.NET Routing with Optional URL Segments

I am working on an ASP.NET MVC task list and I would like to get an idea of ​​URL routing when filtering the list. I have an action method defined like this:

public ActionResult List(int categoryID, bool showCompleted, TaskFilter filter);

enum TaskFilter { MyTasks, MyDepartmentTasks, AllTasks }

      

I want my urls to look like this:

/Tasks/Category4/MyTasks/ShowCompleted/
/Tasks/Category4/MyDepartment
/Tasks/Category4/

      

The segment Category#

will always be present. I would like the segment to MyTasks|MyDepartment|AllTasks

be optional, default AllTasks

if it is missing. I would also like it to ShowCompleted

be optional, default false.

Is this kind of routing possible, or will I have to backtrack and just use the request parameters?

Follow-up / additional credit question: What if I also wanted the fourth parameter of the action method to filter by the due date of the task that looked like Today|Day2Through10

(default Today

if missing)?

+2


source to share


2 answers


Below is your first question with minor modifications:

routes.MapRoute(
    "t1",
    "Tasks/Category{categoryID}",
    new
    {
        controller = "Task",
        action = "List",
        showCompleted = false,
        strFilter = TaskFilter.AllTasks.ToString()
    }
    );

routes.MapRoute(
    "t2",
    "Tasks/Category{categoryID}/{strFilter}/",
    new
    {
        controller = "Task",
        action = "List",
        showCompleted = false
    }
);

routes.MapRoute(
    "t3",
    "Tasks/Category{categoryID}/{strFilter}/ShowCompleted",
    new { controller = "Task", action = "List", showCompleted = true }
    );

      

You will need to change the List method so that it starts out like this:



public ActionResult List(int categoryID, bool showCompleted, string strFilter)
{
    TaskFilter filter = (TaskFilter)Enum.Parse(typeof(TaskFilter), strFilter);

      

For your second request, you just need to use {Day2} and pass it to ActionResult. You should be able to figure this out from what I have given you.

+3


source


Take a look at the MvcContrib library . Here's an example of a free interface for adding restricted routes: http://www.codinginstinct.com/2008/09/url-routing-available-in-mvccontrib.html



0


source







All Articles