David
David

Reputation: 16130

asp.net mvc - inconsistent rendering of ActionLink

I have a controller which accepts URLs in the following two formats:

Obviously it's the same view being used in each instance - one of my design goals is to use the same view for adding and editing purposes.

The master page contains a link to the add page like this:

@Html.ActionLink("Add", "AddOrEdit", "Network")

Ordinarily this renders correctly as /Network/AddOrEdit.

However, when I am on the edit page (i.e. the current URL is in the format Network/AddOrEdit/[id]), then the Add link renders with that ID on the end - so the add link actually points to the edit page. This is not what I want!

So for some reason MVC seems to be allowing the current ID from the query string to interfere with the rendering of the ActionLink.

Any suggestions what I can do about this? :(

Upvotes: 3

Views: 401

Answers (2)

archil
archil

Reputation: 39501

Your guessing is right. MVC routing mechanism may reuse route variables from the current request to generate outgoing route data. That's why the id parameter is populated from the current request. You should explicitely specify id when generating link

@Html.ActionLink("Add", "AddOrEdit", "Network", new { id = String.Empty }, null)

And when routing system sees route with optional id parameter, and route value with string.Empty, it generates link without id in the end

Upvotes: 4

Daryl Teo
Daryl Teo

Reputation: 5495

Tried this myself:

@Html.ActionLink("Add", "AddOrEdit", "Network", new { id = UrlParameter.Optional })

Apparently, this one works too.

@Html.ActionLink("Add", "AddOrEdit", "Network", new { id = String.Empty })

Hopefully this works for you too.

Upvotes: 2

Related Questions