代码之家  ›  专栏  ›  技术社区  ›  ck3g

在ASP.NET MVC2中按项目名称访问项目

  •  0
  • ck3g  · 技术社区  · 15 年前

    问候语。我如何通过他们的名字访问我的文章或帖子? 例如:Like at stackoverflow可以通过名称访问此问题 access to article by article name in ASP.NET MVC2 在asp-net-mvc2中逐条访问

    2 回复  |  直到 8 年前
        1
  •  0
  •   Community CDub    8 年前

    在堆垛机上 name access to article by article name in ASP.NET MVC2 以及这个问题的链接。生成包含 名称 在URL中,您可以定义以下路由:

    routes.MapRoute(  
        "NameIdRoute",  
        "{controller}/{action}/{id}/{name}",  
        new { controller = "Home", action = "Index", id = UrlParameter.Optional, name = UrlParameter.Optional },
        new { id = @"\d+" }  
    );
    

    <%: Html.ActionLink("some text", "action", new { id = Model.Id, name = Model.Name }) %>
    
        2
  •  0
  •   tvanfosson    15 年前

    创建允许将名称指定为url的一部分的路由。请注意,它可能没有实际用于解析文章,因为它可能不是唯一的。id是实际用于查找和显示正确文章的信息位,但是名称是上下文的url的一部分。

    routes.MapRoute(
        "Question",
        "{controller}/{id}/{name}",
        new { controller = "questions", action = "show", id = UrlParameter.Optional, name = UrlParameter.Optional },
        new { id = "[0-9]+" } // constraint to force id to be numeric
    );
    

    <%= Html.ActionLink( "questions", new { id = Model.ID, name = Model.NameForUrl } ) %>
    

    请注意,如果您有多个可能匹配的路由,则可能需要使用RouteLink并按名称指定路由。还有,秩序很重要。