0

This worked yesterday, and I must have changed something at some point, but the url path to the stylesheet no longer works with the following code:

@section Styles {
    @{
        string path = Url.Content("~") + Model.CssPath;
        <link href="path" rel="stylesheet" type="text/css" />
    }
}

When I write out 'path' to the page, it's //Content/site.css. If I browse to http://localhost:59278/Content/site.css, it works. But, the link path is looking at http://Content/site.css.

Why?

Daniel Minnaar
  • 5,865
  • 5
  • 31
  • 52

2 Answers2

1

When you use:

Url.Content("~")

it gives you the root path of your site, always ending in /.

In this case, it is '/' as your local server doesn't have any subpath. When you deploy to another server, it may be "/MySite/SubPath/etc/" (still ending in '/').

As stated in the comments, Model.CssPath is "/Content/site.css"

So locally it is:

"/" + "/Content/site.css" = "//Content/site.css"

but when deployed, might be:

"/MySite/SubPath/etc/" + "/Content/site.css" = "/MySite/SubPath/etc//Content/site.css"

You can:

Simply change your Model.CssPath to a relative path (without leading '/') - ie "Content/site.css"

or

always use the equivalent of System.IO.Path.Combine when combining paths:

string path = new Uri(Url.Content("~"), Model.CssPath).ToString();
freedomn-m
  • 27,664
  • 8
  • 35
  • 57
  • You nailed it. Running my code behaves entirely different when deployed to a server using more paths. After removing the leading '/', and including `Url.Content("~")`, it works flawlessly. However, using the Path.Combine method should eliminate the problem even with incorrect slashes. Thank you. – Daniel Minnaar Aug 06 '15 at 09:26
  • Worth reviewing the comments against [this post](http://stackoverflow.com/questions/372865/path-combine-for-urls) as `new Uri` may not behave exactly like `Path.Combine` – freedomn-m Aug 06 '15 at 09:47
0

Change it to:

<link href="@path" rel="stylesheet" type="text/css" />

Using @path tell the Razor viewengine parser to pick out the variable path from the Razor server-side code context, and dump it's value into the HTML markup.

EDIT:

Interesting. I have the following in a view:

@{
    string path = Url.Content("~") + "Site.css";
}

<link href="@path" rel="stylesheet" type="text/css" />

The renderd HTML looks like this:

<link href="/Content/site.css" rel="stylesheet"/>

I'm not sure how // is appearing in your url.

EDIT:

Based on your comment, it sounds like Model.CssPath contains /Content/ which causes Url.Content to get into a mess, and that you simply need to just do:

href="@Model.CssPath"

Jason Evans
  • 28,906
  • 14
  • 90
  • 154