URL.Action() including route values
Asked Answered
K

2

72

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 }
        );    
Krystinakrystle answered 1/10, 2013 at 2:36 Comment(2)
Did you check your whether your routes registrations are correct?Recognition
What do you mean? Its pretty much the standard one that came in with the default templateKrystinakrystle
B
116

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>
Bulwark answered 1/10, 2013 at 7:59 Comment(2)
How can we do this in asp.net core? There is no UrlParameter.OptionalTetrasyllable
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 typesAnderson
U
-4

You also can use in this form:

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

Uncovenanted answered 25/9, 2017 at 14:7 Comment(1)
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: github.com/ASP-NET-MVC/aspnetwebstack/blob/master/src/…Diaphanous

© 2022 - 2024 — McMap. All rights reserved.