ASP.NET MVC Routes: How to name an action something completely different than in URL

╄→尐↘猪︶ㄣ 提交于 2019-12-08 11:19:35

问题


This is a continuation of a couple of previous questions I've had. I have a controller called UserController that I'd like to handle actions on two types of objects: User and UserProfile. Among other actions, I'd like to define an Edit action for both of these objects, and within UserController. They'll need to be separate actions, and I don't mind calling them EditUser and EditProfile in the controller, but I'd prefer if the URL's looked like this:

http://www.example.com/User/Edit/{userID}

and

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

Does anyone know how to achieve these routes, given the restraint for the actions being in the same controller?

And for context, previous questions are here and here

Thanks.


回答1:


Just an suggestion, but can't you do something like this to map the correct routes?

routes.MapRoute(
    "ProfileRoute", // Route name
    "User/Edit/{userProfileID}", // URL with parameters
    new { controller = "User", action = "EditUser" } // Parameter defaults
);

routes.MapRoute(
    "ProfileEditRouet", // Route name
    "User/Profile/Edit/{userProfileID}", // URL with parameters
    new { controller = "User", action = "Editprofile" } // Parameter defaults
);

EDIT: Then in your controller create two seperate methods called EditUser(guid userId) and Editprofile(guid userId)




回答2:


You could try something like the following: (untested)

routes.MapRoute(
    "EditUser",
    "User/Edit/{userID}", 
    new { controller = "User", action = "EditUser" });

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

EDIT:

Using MvcContrib (available from http://mvccontrib.codeplex.com/) the syntax is slightly clearer:

(using MvcContrib.Routing;)

MvcRoute
    .MappUrl("User/Edit/{userID}")
    .WithDefaults(new { controller = "User", action = "EditUser" })
    .AddWithName("EditUser", routes);

MvcRoute
    .MappUrl("User/Profile/Edit/{userProfileID}")
    .WithDefaults(new { controller = "User", action = "EditProfile" })
    .AddWithName("EditProfile", routes);



回答3:


using MvcContrib.Routing;

public class UserController : Controller
{
    [UrlRoute(Path = "User/Edit/{userID}")]
    public ActionResult UserEdit(int userID)
    { 

    }
}


来源:https://stackoverflow.com/questions/4080897/asp-net-mvc-routes-how-to-name-an-action-something-completely-different-than-in

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