href path in aspx files in area
-
19-09-2019 - |
Question
I am continually testing the new feature of ASP.NET MVC 2 Preview 2 called: "Areas within one project". Currently I have a problem with linking to css and js files from within aspx code.
When the url points to an url without the id, everything works fine:
The problem appears when the url contains the parameter:
then the page cannot find css and js files from /content and /scripts.
I think the problem is related to routing. I have standard routing rules set, eg:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
AreaRegistration.RegisterAllAreas();
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
and in the area's route config:
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"admin_default",
"Admin/{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }
);
}
An example resource href in aspx file:
<link href="../../Content/datatables.css" rel="stylesheet" type="text/css" />
Can anyone suggest a solution to resolve the problem of bad resource href?
Solution
When you are using URL routing, you don't know how/many/path/parts there are going to be in your URL in advance. So you can't use path-relative URLs at all: you don't know how many ‘..’ segments you are going to need.
Instead, use rooted URLs:
<link href="/Content/datatables.css" rel="stylesheet" type="text/css" />
If your application can be mounted on a non-root URL (eg. under one of your area
s, you must output that area name as part of the rooted URL. (Presumably this is obtained using AreaRegistrationContext.AreaName
.)
OTHER TIPS
How about this, set runat="server" attribute.
<head runat="server">
<link href="~/Content/datatables.css" rel="stylesheet" type="text/css" runat="server" />
...