I have an ASP.Net MVC 4 app and am using the Url.Action helper like this: @Url.Action("Information", "Admin")
This page is used for both adding a new and edit an admin profile. The URLs are as follows:
Adding a new: http://localhost:4935/Admin/Information Editing Existing: http://localhost:4935/Admin/Information/5 <==Admin ID
When I'm in the Editing Existing
section of the site and decide that I would like to add a new admin I click on the following link:
<a href="@Url.Action("Information", "Admin")">Add an Admin</a>
The problem however that the above link is actually going to http://localhost:4935/Admin/Information/5
. This only happens when I'm in that page editing an existing admin. Anywhere else on the site it links correctly to http://localhost:4935/Admin/Information
Has anyone else seen this?
UPDATE:
RouteConfig:
routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } );
Generates a fully qualified URL to an action method for the specified action name and route values. Generates a fully qualified URL to an action method by using the specified action name, controller name, and route values.
You can concat the client-side variables with the server-side url generated by this method, which is a string on the output. Try something like this: var firstname = "abc"; var username = "abcd"; location. href = '@Url.
Route values are the values extracted from a URL based on a given route template. Each route parameter in a template will have an associated route value and is stored as a string pair in a dictionary.
RouteData is a property of the base Controller class, so RouteData can be accessed in any controller. RouteData contains route information of a current request. You can get the controller, action or parameter information using RouteData as shown below. Example: RouteData in MVC.
outgoing url in mvc generated based on the current routing schema.
because your Information action method require id parameter, and your route collection has id of your current requested url(/Admin/Information/5), id parameter automatically gotten from existing route collection values.
to solve this problem you should use UrlParameter.Optional:
<a href="@Url.Action("Information", "Admin", new { id = UrlParameter.Optional })">Add an Admin</a>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With