views:

2098

answers:

4

I have the following ActionLink in my view

<%= Html.ActionLink("LinkText", "Action", "Controller"); %>

and it creates the following URL http://mywebsite.com/Controller/Action

Say I add an ID at the end like so: http://mywebsite.com/Controller/Action/53 and navigate to the page. On this page I have the markup I specified above. Now when I look at the URL it creates it looks like this:

http://mywebsite.com/Controller/Action/53 (notice the addition of the ID)

But I want it to remove the ID and look like it did originally, like this http://mywebsite.com/Controller/Action (notice no ID here)

Any ideas how I can fix this? I don't want to use hard coded URLs since my controller/actions may change.

+6  A: 

The solution is to specify my own route values (the third parameter below)

<%= Html.ActionLink("LinkText", "Action", "Controller", new { id=string.empty }, null) %>

side note: Garry helped answer this but for some reason his answer was deleted.

codette
Thanks for this answer, I needed it for another circumstance but you hit the nail right on the head with that trailing null!
Soulhuntre
This seems a little kludgey... I need to do the same thing but I think I might have to create a new extension method like Arnis L posted below
Jiho Han
Also this seems like the functionality should be built-in to the framework since this situation comes up often. For example, having a menu, you don't want the menu link to contain all of the parameters, just the action
Jiho Han
i m using .NET 4 and mvc2 but string.empty does not solve the above mentioned problem and actionlink still keeping the ambient values
Muhammad Adeel Zahid
A: 

Don't know why, but it didn't work for me (maybe because of Mvc2 RC). Created urlhelper method =>

 public static string
            WithoutRouteValues(this UrlHelper helper, ActionResult action,params string[] routeValues)
        {
            var rv = helper.RequestContext.RouteData.Values;
            var ignoredValues = rv.Where(x=>routeValues.Any(z => z == x.Key)).ToList();
            foreach (var ignoredValue in ignoredValues)
                rv.Remove(ignoredValue.Key);
            var res = helper.Action(action);
            foreach (var ignoredValue in ignoredValues)
                rv.Add(ignoredValue.Key, ignoredValue.Value);
            return res;
        }
Arnis L.
A: 

It sounds like you need to register a second "Action Only" route and use Html.RouteLink(). First register a route like this in you application start up:

routes.MapRoute("ActionOnly", "{controller}/{action}", new { controller = "Home", action = "Index" } );

Then instead of ActionLink to create those links use:

Html.RouteLink("About","ActionOnly")
Brian
A: 

Another way is to use ActionLink(HtmlHelper, String, String, RouteValueDictionary) overload, then there are no need to put null in the last parameter

<%= Html.ActionLink("Details", "Details", "Product", new RouteValueDictionary(new { id=item.ID })) %>
Murilo Lima