我正在开发一个ASP.NET MVC任务列表,我想在过滤列表时对URL路由感兴趣。我有一个像这样定义的动作方法:
public ActionResult List(int categoryID, bool showCompleted, TaskFilter filter);
enum TaskFilter { MyTasks, MyDepartmentTasks, AllTasks }
我希望我的网址看起来像这样:
/Tasks/Category4/MyTasks/ShowCompleted/
/Tasks/Category4/MyDepartment
/Tasks/Category4/
Category#
段始终存在。我希望MyTasks|MyDepartment|AllTasks
段是可选的,如果不存在则默认为AllTasks
。我也希望ShowCompleted
是可选的,默认为false。
这种路由是否可行,或者我将不得不退回并只使用查询字符串参数?
跟进/额外信用问题:如果我还希望操作方法的第四个参数按任务截止日期过滤看似Today|Day2Through10
(默认为Today
,如果不存在),该怎么办?
答案 0 :(得分:3)
以下内容涵盖您的第一个问题,稍作修改:
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 }
);
您需要将List方法更改为如下所示:
public ActionResult List(int categoryID, bool showCompleted, string strFilter)
{
TaskFilter filter = (TaskFilter)Enum.Parse(typeof(TaskFilter), strFilter);
对于第二个查询,您只需要使用{Day2}并将其传递给ActionResult。你应该能够从我给你的东西中找到它。
答案 1 :(得分:0)
查看MvcContrib库。以下是添加具有约束的路径的流畅界面的示例:http://www.codinginstinct.com/2008/09/url-routing-available-in-mvccontrib.html