Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net mvc Html.ActionLink() keeping route value I don't want

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.

like image 246
codette Avatar asked Apr 23 '09 07:04

codette


People also ask

What is difference between HTML ActionLink and URL action?

Yes, there is a difference. Html. ActionLink generates an <a href=".."></a> tag whereas Url. Action returns only an url.

What is the main purpose of HTML helper of ActionLink in ASP.NET MVC?

Html. ActionLink creates a hyperlink on a view page and the user clicks it to navigate to a new URL. It does not link to a view directly, rather it links to a controller's action.

What is the default setting for route config in MVC?

Routing in ASP.NET MVC By default route is: Home controller - Index Method. routes. MapRoute has attributes like name, url and defaults like controller name, action and id (optional).


2 Answers

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

<%= Html.ActionLink("LinkText", "Action", "Controller",      new { id=string.Empty }, null) %> 
like image 182
codette Avatar answered Sep 23 '22 05:09

codette


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") 
like image 39
Brian Cauthon Avatar answered Sep 25 '22 05:09

Brian Cauthon