70

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 }
        );    
hjavaher
  • 2,589
  • 3
  • 30
  • 52

2 Answers2

114

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>
Emad Feiz
  • 1,545
  • 1
  • 10
  • 17
  • 11
    How can we do this in asp.net core? There is no `UrlParameter.Optional` – MOD Oct 14 '16 at 08:25
  • in ASP.NET Core seems like `new { id = "" }` might work, at least in my case when Id was a guid type, so I suppose it may work also for other non-string types – infografnet Mar 28 '21 at 11:23
-4

You also can use in this form:

<a href="@Url.Action("Information", "Admin", null)"> Admin</a>

SSadig
  • 3
  • 1
  • 5
  • 2
    No you cannot. Setting the last parameter of the Url action helper as null as the same effect as ignoring it. It will use the overloaded method with only two parameters where the routeValues object is null. Please refer to the code source linked below for more details: https://github.com/ASP-NET-MVC/aspnetwebstack/blob/master/src/System.Web.Mvc/UrlHelper.cs – webStuff Sep 12 '18 at 09:07