Friday, April 17, 2009

Linking resources in ASP.NET MVC

Working on web sites that have dynamic URLs (like the ones in ASP.NET MVC or JSF) poses one difficulty: you never know where to look for resources such as images or CSS files. This is due to the fact that the same view can have more than one address. Let me give you an example:

/Demo/ -> this should render the default controller (HomeController) with the default view (Index.aspx).
/Demo/Home -> this should render the specified controller (again HomeController) with the default view (Index.aspx)
/Demo/Home/Index -> this should render the specified controller (again HomeController) with the specified view (Index.aspx)

So how do you go about specifying an URL for resources in this case? Well there are different ways to do that.

1. You could create and use an Html helper method to do that.
2. You could hard-code the absolute paths (like /Demo/Content/Index.css for example)
3. You could make use of the runat attribute and use relative paths.

I personally dislike the first and second options. They tend to introduce mess to my otherwise clear code. The third option is in my opinion the best one.
Here's an example of how you'd create a link to a CSS:


<link type="text/css" href="~/Content/Site.css" runat="server" />


Happy coding!

No comments: