ASP.NET MVC mapping URLs different to {controller}/{action} with areas

只愿长相守 提交于 2019-12-11 06:07:22

问题


I want to be able to map a route using a URL that doesn't conform to the {controller}/{action}/{id} format. The mapping looks like:

routes.CreateArea("Root", "MyApp.Web.Controllers",
    routes.MapRoute("Category-List", "Category/{category}", 
        new { controller = "Category", action = "List" }),
    routes.MapRoute("Default", "{controller}/{action}/{id}", 
        new { controller = "Home", action = "Index", id = "" })
);

Where I have a CategoryController with an action List(string category).

I was hoping to be able to use this in my view:

<%= Html.ActionLink<CategoryController>(
    c => c.List(category.UrlFriendlyName), 
    category.Name)%>

(line breaks added for readability)

All this produces is a link with href="". Removing the route from the "Root" area produces the correct result. Is it possible to use this type of mapping with the generic ActionLink helper or do I have to resort to RouteLink or something similar with hard coded values?

I also tried the following with no success:

<%= Html.ActionLink(category.Name, "List", "Category", 
new { category = category.UrlFriendlyName }) %>

回答1:


Not ideal, but can you use the route name approach?

<%= Html.RouteLink("your link", "Category-List", new {category = "foo"})%>



回答2:


By sight, what you have written looks correct for producing the URL you want. Have you tried using the non-strongly typed Html.ActionLink method to see if that works?




回答3:


I don't see anything in your call to ActionLink which would cause the routing system to realize which route to use. Instead, I would recommend using Html. RouteLink, which allows you to specify a route by name. This will ensure that the correct route is matched.

Update: are you doing a cross-area link? (In other words, is the area you're linking to different than the area containing the link?) If so, you must specify the area in your call to ActionLink/RouteLink. If not, does RouteLink work?

I don't think this is what is causing the problem, but I noticed that your Category-List route has no constraints, and I think it should probably be constrained to the Category controller.



来源:https://stackoverflow.com/questions/638362/asp-net-mvc-mapping-urls-different-to-controller-action-with-areas

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