区域内的自定义路由

时间:2010-09-27 08:41:51

标签: asp.net-mvc-2 asp.net-mvc-routing asp.net-mvc-areas

我在MembersAreaRegistration文件中有一个名为Members的区域和以下注册路由:

context.MapRoute(
     "Members_Profile",
     "Members/Profile/{id}",
     new { controller = "Profile", action = "Index", id = UrlParameter.Optional },
     new string[] { "MyProject.Web.Mvc.Areas.Members.Controllers" }
     );

context.MapRoute(
     "Members_default",
     "Members/{controller}/{action}/{id}",
     new { controller = "Home", action = "Index", id = UrlParameter.Optional },
     new string[] { "MyProject.Web.Mvc.Areas.Members.Controllers" }
     );

我希望能够映射以下网址:

~/Members (should map ~/Members/Home/Index )
~/Members/Profile/3 (should map ~/Members/Profile/Index/3)

通过此路线注册一切正常。但是,我添加了以下URL:

~/Members/Profile/Add 

我得到了错误:

  

“参数字典包含非可空类型'System.Int32'的参数'id'的空条目,用于'MyProject.Web.Mvc.Areas中的方法'System.Web.Mvc.ActionResult Index(Int32)' .Members.Controllers.ProfileController'。可选参数必须是引用类型,可以为空的类型,或者声明为可选参数。“

我也想要网址

~/Members/Profile/Edit/3

为了让所有这些网址正常运行,我应该修改哪些内容?

1 个答案:

答案 0 :(得分:3)

在您已经定义的路线之前,您需要添加几条额外的路线。这是因为这些是您希望在已有的更通用路线之前选择的特定路线。

context.MapRoute(
     "Members_Profile",
     "Members/Profile/Add",
     new { controller = "Profile", action = "Add" },
     new string[] { "MyProject.Web.Mvc.Areas.Members.Controllers" }
     );

context.MapRoute(
     "Members_Profile",
     "Members/Profile/Edit/{Id}",
     new { controller = "Profile", action = "Edit", id = UrlParameter.Optional },
     new string[] { "MyProject.Web.Mvc.Areas.Members.Controllers" }
     );