Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

c# - Using site root relative links in Razor

I have a website that is working fine with Razor (C#) all the coding is working properly when I use my local testing (WebMatrix IIS).

When I put it "online" on my server the website is not at the root of the site it self

For example:

http:// intranet.mycompany.com/inform

That's basically the "root" of my folder structure so all my folders starts from there (css file default.cshtml... and so on)

My "_PageStart.cshtml" sees it properly cause when I access my site from the link http://intranet.mycompany.com/inform it gives me the Layout I have configured in _PageStart.cshtml (and it really show the layout + the rendered default.cshtml)

BUT nothing else is getting the proper path, for example :

<img src="~/images/logos/hdr.png" />

The img holder is there I can see it but shows that the link is broken... when I Right-Click the img holder and do properties to see where the files should be it shows me :

http:// intranet.mycompany.com/images/logos/hdr.png

So it's going to the "full" root not the relative root...

How can i fix that ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have to use relative paths all over your app:

~ won't work within static html code.

You can write

<img src="@Url.Content("~/images/logos/hdr.png")" />

or

<img src="../images/logos/hdr.png" />

The first approach is good for layout files where your relative path might be changing when you have different length routing urls.

EDIT

Regarding to your question about normal links:

When linking to another page in your app you don't specify the view file as the target but the action which renders a view as the result. For that you use the HtmlHelper ActionLink:

@Html.ActionLink("Linktext", "YourController", "YourAction")

That generates the right url for you automatically:

<a href="YourController/YourAction">Linktext</a>

EDIT 2

Ok, no MVC - so you have to generate your links yourself.

You have to use relative paths, too. Don't start any link with the / character!

<a href="linkOnSameLevel.cshtml">Link</a>
<a href="../linkOnParentLevel.cshtml">Link</a>
<a href="subFolder/linkOnOneLevelDown.cshtml">Link</a>

EDIT 3

When using Layout pages you can use the Hrefextension method to generate a relative url:

<link href="@Href("~/style.css")" ...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...