Reputation: 5069
In my mvc3 razor project my I have action link
@Html.ActionLink("ActionLinkName","Count","Home",new{id = 3})
This generates localhost/Home/Count/3
but I want it to create localhost/Home/Count?id=3
What changes in route should I make ?
Upvotes: 1
Views: 1407
Reputation: 11319
This is because the default route that's used with new MVC projects includes an {id}
segment. Removing that segment from your default route will make your existing code produce a query string.
Change this:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
To this:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}", // URL with parameters
new { controller = "Home", action = "Index" } // Parameter defaults
);
Upvotes: 2
Reputation: 49095
Since the default (fallback) route that Asp.Net registers is including an {id}
parameter in the url pattern:
// Default
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Your generated url adheres to this fallback pattern ({controller}/{action}/{id}
) and appends your id
using /{id}
.
You'll need to register a custom route before the default route to exclude the {id}
:
routes.MapRoute(
name: "Count",
url: "Home/Count",
defaults: new { controller = "Home", action = "Count" }
);
You can also try to remove the {id}
from the default pattern (if it won't affect other actions) or change your id
parameter in the Count
action to a different name.
Upvotes: 1
Reputation: 15866
remove {id}
from default config
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new {
controller = "Home",
action = "Index",
id = UrlParameter.Optional }
);
}
TO
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}",
defaults: new {
controller = "Home",
action = "Index" }
);
}
Upvotes: 0