How to Prevent .NET MVC Url.Action() Method from Inserting ID in a Route

Listen to this text

I had this issue that took me a solid two hours to debug. I thought I’d quickly write about it for the common good, in case it saves collective time for humanity: time that can be better wasted on other non-productive endeavors, like refreshing reddit, or reading some awful blog (not this one of course).

It appears that the Url.Action() method in MVC will take whatever current value is in the ID field on your browser, and sometimes plug this into a new route, even when you are explicitly not doing so.

For instance, Suppose you navigate to a route /User/Profile/855 where 855 is the ID. And you want a link to just /User/Profile/(no id). Well, if you use Url.Action() is will “helpfully”, put the 855 id in there for you, even if you ask nicely not to. It’s like a toddler trying to be helpful while you make coffee and so you let them hold the measuring cup with all the coffee grounds and then instead of putting it in the coffee maker, they miss and drop it all on the floor. But… I digress 🙂

So, the way to force MVC’s Url.Action() method to NOT do this, is quite simple, you just put in an empty string when constructing the action, so in this example it’s just:

@Url.Action("Profile", "User", new { id = "" })