【问题标题】:Why my view action links including current action params in MVC3为什么我的视图操作链接包括 MVC3 中的当前操作参数
【发布时间】:2012-11-13 01:54:33
【问题描述】:

我正在开发一个 MVC3 应用程序。

在我看来,我使用@Html.ActionLink 作为锚链接。一切正常。 但这些链接在链接中包含当前 url 的参数。

如果我当前的链接是http://localhost:25466/Blog/all/2

正在生成的操作链接是http://localhost:25466/Blog/Blog/shoes/2

在上面的链接中,实际上我并没有在 url 中包含“2”。但它仍在添加中。

我的路线配置是

routes.MapRoute(
                "Blog", "Blog/Blog/{tag}/{id}",
            new { controller = "Blog", action = "Blog", tag = UrlParameter.Optional,id="1" }
            );

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = "1" },
                constraints: new { id = @"\d+" }
            );

而我的行动是

 public ActionResult All(int id)
        {
            var context = new BlogCore.DbContext.BlogContext();
            var list = context.Get(id,20);
            return View(list);
        }

        public ActionResult Blog(string tag,int id)
        {
            var context = new BlogCore.DbContext.BlogContext();
            var list = context.Get(HttpUtility.UrlEncode(tag), id, 20);
            return View("All", list);
        }

这就是我使用 actionlink 生成锚链接的方式

@Html.ActionLink(blog.PostTitle, "Blog", "Blog", new { tag = blog.PostRewriteName }, null)

如何避免动作链接中的2。

提前致谢。

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-4 asp.net-mvc-routing asp.net-mvc-areas


    【解决方案1】:

    我认为您必须明确设置该参数,例如:

    @Html.ActionLink(blog.PostTitle, "Blog", "Blog", new { tag = blog.PostRewriteName, id = 1 }, null)
    

    我相信在使用 ActionLink 创建链接时会考虑实际的视图字典。

    【讨论】:

    • 感谢您的重播。其实我试过了,但是没用。
    • Aahhh....对不起,我正在尝试使用不同的链接。它正在工作。但是操作链接在构建时是否考虑了 url 参数?
    • 我猜不是直接,而是因为它们最终出现在 RouteValueDictionary 中:是的
    【解决方案2】:

    MVC 将使用当前查询字符串中的任何变量来查找生成 url 的路由。所以你的变量 id 将被包括在内。为避免这种情况,您需要在传递给 ActionLink 帮助器的路由数据中将 id 显式设置为 null:

    @Html.ActionLink(blog.PostTitle, "Blog", "Blog", new { tag = blog.PostRewriteName, id = null }, null)
    

    【讨论】:

      猜你喜欢
      • 2011-07-24
      • 1970-01-01
      • 1970-01-01
      • 2012-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多