What’s in a [Route] Name?

In ASP.NET MVC-land, there’s no such thing as a location that you or I think of. It’s all controllers, actions, and route values.

Someone forgot to tell relative URLs that.

If you’re using a relative URL in ASP.NET MVC, sooner or later you’ll bump up into the same problem I did.

You have a route, it looks like this:

         routes.MapRoute("Edit",
                "{controller}/{action}/{id}/{*pagename}",
                new { controller = "Page", action = "Edit", id = "", pagename="" }
                );

 

You would expect that anything pointing to:

http://localhost:3919/Page/Edit/11?pagename=news

and:

http://localhost:3919/Page/Edit/11/news

would match, right?

They do. Except when you want to include a physical resource. You know, like a script.

Your script folder is a physical location, these routes are not. But the script doesn’t know that.

If you were to drag the script from the Visual Studio IDE to the editor window, you’d get something like the following:

<script src="../../Scripts/tinyMCE/tiny_mce.js" type="text/javascript"></script>

Guess what? That matches the first route, but not the second. Ooops.

If you’re going to use a static resource in ASP.NET MVC, be aware of two things:

1. controllers and route values aren’t tied to any particular paths.

2. Static resources care about paths.

I blame part of this on Visual Studio. ASP.NET MVC shouldn’t let you shoot yourself in the foot so easily. It knows you’re dealing with MVC, it should give you absolute paths when you drag and drop items.

Who has two thumbs and feels embarassed that he spent an hour debugging this issue, down to a line-by-line compare of the differing files? This guy.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s