3

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

  • Network/AddOrEdit -> renders a blank form on a page to add a new network object
  • Network/AddOrEdit/[id] -> renders a page with prepopulated form to edit the network object with ID [id]

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? :(

1

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

This solved the problem. Guess I just don't know my ActionLink overloads well enough!
2

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.

3 Comments

Thanks, but I don't think you've understood the question. I want the link to render WITHOUT an ID on the end.
Thanks for coming back on this Daryl, but this didn't work. Bizarrely, it just appended the text 'Length=7' onto the end of the query string.
One of those all-important nulls.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.