Asp.Net Mvc中的路由问题

时间:2009-08-18 16:29:12

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

我有一个标有特定“主题”的谜题列表。想一下用特定类别标记的stackoverflow上的问题。

我正在尝试设置我的路线,以便它像这样工作:

http://www.wikipediamaze.com/puzzles/themed/Movies http://www.wikipediamaze.com/puzzles/themed/Movies,Another-Theme,And-Yet-Another-One

我的路线设置如下:

    routes.MapRoute(
        "wiki",
        "wiki/{topic}",
        new {controller = "game", action = "continue", topic = ""}
        );

    routes.MapRoute(
        "UserDisplay",
        "{controller}/{id}/{userName}",
        new {controller = "users", action = "display", userName=""},
        new { id = @"\d+" }
        );

    routes.MapRoute(
        "ThemedPuzzles",
        "puzzles/themed/{themes}",
        new { controller = "puzzles", action = "ThemedPuzzles", themes = "" }
        );

    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new {controller = "Home", action = "Index", id = ""} // Parameter defaults
        );

我的控制器看起来像这样:

public ActionResult ThemedPuzzles(string themes, PuzzleSortType? sortType, int? page, int? pageSize)
{
    //Logic goes here
}

视图中的我的Action链接调用如下所示:

        <ul>
        <%foreach (var theme in Model.Themes)
          { %>
            <li><%=Html.ActionLink(theme, "themed", new {controller = "puzzles", themes = theme})%></li>
            <% } %>
        </ul>

然而,我遇到的问题是:

生成的链接显示如下:

http://www.wikipediamaze.com/puzzles/themed?themes=MyThemeNameHere

要添加此问题,控制器操作上的“Themes”参数始终为null。它永远不会将querystring参数转换为控制器操作参数。但是,如果我手动导航到

http://www.wikipediamaze.com/puzzles/themed/MyThemeNameHere http://www.wikipediamaze.com/puzzles/themed/MyThemeNameHere,Another-ThemeName

一切正常。我错过了什么?

提前致谢!

3 个答案:

答案 0 :(得分:1)

您对actionName的通话的Html.ActionLink参数(第二个参数)与您在"ThemedPuzzles"路线中指定的操作不符。

非常类似菲尔的建议,试试:

<%= Html.ActionLink(theme, "ThemedPuzzles", new { controller = "puzzles", themes = theme }) %>

或者您可以直接调用路径(因为它已命名),而无需指定控制器或操作(因为它们将从路由默认值中选取):

<%= Html.RouteLink(theme, "ThemedPuzzles", new { themes = theme }) %>

答案 1 :(得分:0)

试试这个:

<li><%=Html.ActionLink(theme, "themed", new {controller = "puzzles", **action="ThemedPuzzles"** themes = theme})%></li>

您需要指定操作,因为您有默认操作,但您的网址中没有{action}参数。这种行为的原因是假设有另一条路径,如

routes.MapRoute(
        "SpecialThemedPuzzles",
        "puzzles/special-themed/{themes}",
        new { controller = "puzzles", action = "SpecialThemedPuzzles", themes = "" }
        );

您如何生成此路线的网址?除非我们有办法将这条路线与你的其他主题路线区分开来,否则你将无法做到。因此,在这种情况下,当Routing看到defaults字典中的参数不是实际URL中的参数时,它要求您指定该值以区分这两个路由。

在这种情况下,它需要您指定区分路线的操作。

答案 2 :(得分:0)

在路由声明中,尝试在控制器方法中指定每个输入参数。

routes.MapRoute(        
"ThemedPuzzles",        
"puzzles/themed/{themes}",        
new { controller = "puzzles", action = "ThemedPuzzles", themes = "",  sortType = "", page="", pageSize="" }        
);

如果你有排序类型,页码和页面大小的默认值,你甚至可以在这里设置它们,所以如果不包括它们,则会传入默认值。