自定义路由
问题描述:
我在MembersAreaRegistration文件中的区域,称为会员及以下注册路线:自定义路由
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)
随着这条路线注册一切正常。不过,我增加了以下网址:
~/Members/Profile/Add
,我得到了错误:
"The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Index(Int32)' in 'MyProject.Web.Mvc.Areas.Members.Controllers.ProfileController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter."
我也想有网址
~/Members/Profile/Edit/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" }
);
我按照你的建议做了一点修改。现在我使用的路线如下(顺序很重要): 1.“Members/Profile/Add” 2.“Members/Profile/{id}” 3.“Members/{controller}/{action }/{id}“ 我摆脱了Edit的路由,因为它被最后一个和最通用的路由所覆盖。感谢您的帮助 – Martin 2010-09-27 09:51:11
很高兴为您提供帮助。请将问题标记为已回答,以便其他人也可以找到答案。 – Clicktricity 2010-09-27 10:20:26