I found this question Can't use relative paths with areas in ASP.NET MVC 2 which is the same issue I am having. Is this still the case in MVC3?
Is there a way to keep content files in an area relative to the area?
So that a layout file in an area can have something like
Without having to either make a fully qualified link, requiring the areas directory and the area name or the solution of the above question which requires a check for each area on each request.
update/edit
I've decided to use both the solution in the above question and the one below (html helper) - depending on the project/situation. My implementation of the above uses app.setting to store the area names and the extensions so that I can just have the module as part of my library.
var context = HttpContext.Current;
var path = context.Request.Path;
var list = ... //code that gets from app.config and then saves it
var extensions = ... // to the cache as non-removable with a dependency on web.config
foreach (var area in list)
{
if (!path.Contains(area + "/")) continue;
foreach (var extension in extensions)
{
if (path.EndsWith("." + extension))
{
context.RewritePath(path.Replace(area + "/", "Areas/" + area + "/"));
}
}
}
I tried the UrlHelperExtensions above for some images which I use in my masterpage as data for a jQuery scrolling banner. I had to add the following else clause so that the helper would return tha path when there was no area:
In my view page I used:
Thanks for posting this solution. Works great with my fix for images.
I had similar problems with my ASP.NET MVC 3 web application and I fixed it writing instead of
this:
where the last mylink is a path like ~/mypath. I used it to link my javascript files, however I didn't try it with images or links so you should try yourself...
I just had a similar problem in a style sheet that I solved by just putting in both relative paths:
You can try creating an extention on HtmlHelper to work this out:
so in your view you can use:
I didn't try the code so correct me if I'm wrong.
I personally like the extension method route, based on the first answer I came up with this and tested that it works ... Instead of using
@Url.Content
, use@Url.ContentArea
and no need to put in '~/', '/' or '../', etc..The helper does some checking to automatically remove these, so just use is like this ...
When you create this Url Helper Extension, your choice, but I created a 'Helpers' folder off the root of the web then I include the
@using YourWebNameSpace.Helpers;
in my_Layout.cshtml
(razor/masterpage) in whatever 'Area' I am in.You can still use
@Url.Content
for references outside the current area (basically you can mix based on the resource needed and its location).in your master page, or any page (Razor only for this example) ...