0

I am working on a MVC3 application.

In my view I am using @Html.ActionLink for anchor links. Every thing working fine. But those links are including the current url's params in the link.

If my current link is http://localhost:25466/Blog/all/2

Action link being generated are http://localhost:25466/Blog/Blog/shoes/2

In the above link actually I am not doing any thing to include '2' in the url. But still it is being added.

My route config are

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+" }
            );

And my actions are

 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);
        }

And this is how I am using actionlink to generate anchor link

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

How can I avoid 2 in the action link.

Thanks in advance.

Charles
  • 50,943
  • 13
  • 104
  • 142
Naresh
  • 2,667
  • 13
  • 44
  • 69

2 Answers2

1

I think you have to explicitly set that parameter, like:

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

I believe the actual view dictionary is taken into account when creating a link with ActionLink.

Grimace of Despair
  • 3,436
  • 26
  • 38
1

MVC will use any variables from the current querystring when finding a route to generate a url. So your variable id will be included. To avoid this, you need to explicitly set id to null in the routedata you pass to the ActionLink helper:

@Html.ActionLink(blog.PostTitle, "Blog", "Blog", new { tag = blog.PostRewriteName, id = null }, null)
Paul Taylor
  • 5,651
  • 5
  • 44
  • 68