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 ...
@Url.ContentArea("Content/style.css") or @Url.ContentArea("Images/someimage.png") :)
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).
namespace YourWebNamespace.Helpers
{
public static class UrlHelperExtensions
{
public static string ContentArea(this UrlHelper url, string path)
{
var area = url.RequestContext.RouteData.DataTokens["area"];
if (area != null)
{
if (!string.IsNullOrEmpty(area.ToString()))
area = "Areas/" + area;
// Simple checks for '~/' and '/' at the
// beginning of the path.
if (path.StartsWith("~/"))
path = path.Remove(0, 2);
if (path.StartsWith("/"))
path = path.Remove(0, 1);
path = path.Replace("../", string.Empty);
return VirtualPathUtility.ToAbsolute("~/" + area + "/" + path);
}
return string.Empty;
}
}
}
in your master page, or any page (Razor only for this example) ...
@using YourWebNamespace.Helpers
<html lang="en">
<head>
<link href="@Url.ContentArea("Content/reset.css")" media="screen" rel="stylesheet" type="text/css" />
<link href="@Url.ContentArea("Content/style.css")" media="screen" rel="stylesheet" type="text/css" />
</head>
<body>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…