ASP.NET MVC Routes: How to define custom route

谁说胖子不能爱 提交于 2019-11-30 09:18:54

问题


I've looked online for an answer to this question, but I honestly can't seem to find a good reference for MVC routes.

I have a UserController for my User objects. One can Edit, Save, View, etc. on the User, so I have actions in that controller to handle each of those. That's all pretty straightforward. But I've recently created a new UserProfile object that one can also edit, view, etc. Rather than create an entirely new controller just for the UserProfile, I'd like to make use of the existing UserController. So to view a user's profile, I'd like the URL to be:

http://www.example.com/User/Profile/{userProfileID}

And to edit, I'd like the URL to be:

http://www.example.com/User/Profile/Edit/{userProfileID}

Each of these actions in the UserController will return a different view page.

How would I go about defining routes to handle this structure? Thanks very much.


回答1:


In your Global.asax file in the RegisterRoutes() method do the following:

routes.MapRoute(
    "ProfileRoute",
    "User/Profile/{action}/{userProfileID}",
    new { controller = "User", action = "Index" });

As pointed out by the comments...this must come BEFORE the Default route.



来源:https://stackoverflow.com/questions/4080224/asp-net-mvc-routes-how-to-define-custom-route

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!