【问题标题】:Mvc: pass id but not show it in friendly urlMvc:传递 id 但不在友好的 url 中显示
【发布时间】:2013-03-11 19:49:43
【问题描述】:

我有一个呈现新闻列表的视图,因为我有一个 href 标记,我需要调用一个 Detail 方法并将新闻 id 传递给它,现在我的 url 中有一个这样的查询字符串 News/Details?id=x... 但我需要类似 News/Details/Category/Title-of-something 的东西,一个带有新闻类别、名称且没有 id 的友好 url

这是我的操作,它有效,但我得到了那个查询字符串

foreach (var item in Model)
{
    <a href='@Url.Action("Details", "News", new { id = item.newsId, category = item.categoryName, name = item.newsName })' title=""> Read More </a>
}

我正在尝试使用 Url.RouteUrl 之类的东西

 routes.MapRoute(
            name: "Details",
            url: "{controller}/{action}/{id}/{category}/{newsName}",
            defaults: new { controller = "News", action = "Details"}
        );

但它永远不会进入详细信息操作结果,而且我需要传递 id 参数来显示一些新闻详细信息,但我不想在友好的 url 中显示它。我真的很困惑如何实现它。提前致谢

【问题讨论】:

  • 路由可能被其他路由覆盖。因此,复制此路线并将其移至顶部。我的意思是,将这条路线放在另一条路线的顶部

标签: asp.net-mvc asp.net-mvc-3 friendly-url


【解决方案1】:

第一个网址正确

<a href='@Url.Action("Details", "News", new { id = item.newsId, category = item.categoryName, newsName = item.newsName })' title=""> Read More </a>

当您看到与路线相关的问题时,您可以Route Debugger

【讨论】:

    【解决方案2】:

    确保您的路线没有被其他路线覆盖。因此,将您的路线放在 RoutConfig.cs 中 将您的代码更改为:

    foreach (var item in Model)
    {
        <a href='@Url.Action("Details", "News", new { id = item.newsId, category = item.categoryName, newsName = item.newsName })' title=""> Read More </a>
    }//change name=item.newsName to newsName=item.newsName
    

    还要确保您的控制器根据您的路由详细信息具有正确的签名:

    public class NewsController : Controller
    {
        public ActionResult Details(int id, string category, string newsName )
    }
    

    【讨论】:

      【解决方案3】:

      试试这个:

      @Html.RouteLink("Read More", "Details", new { action = "Details", id = item.newsId, category = item.categoryName, newsName = item.newsName })
      

      【讨论】:

      • 它工作得很好,所以现在我可以向我的 ActionResult 发送多个参数,并且我拥有和 URL 友好的东西,例如 News/Details/Id/Category/Title-of-something,routes.MapRoute 是对,所以你知道我如何将 id 发送到我的操作结果,并让我的 url 带有类似 News/Details/Category/Title-of-something 的东西而没有 id。谢谢
      【解决方案4】:

      使用:

      <a href='@Url.Action("Details", "News", new { id = item.newsId, category = item.categoryName, newsName = item.newsName })' title=""> Read More </a>
      

      【讨论】:

        猜你喜欢
        • 2019-05-26
        • 2021-12-13
        • 2013-07-27
        • 1970-01-01
        • 2021-12-07
        • 2013-02-14
        • 2012-09-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多