在 Razor 中使用站点根相关链接 [英] Using site root relative links in Razor

查看:19
本文介绍了在 Razor 中使用站点根相关链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 Razor (C#) 运行良好的网站,当我使用本地测试 (WebMatrix IIS) 时,所有编码都正常工作.

当我把它在线"放在我的服务器上时,该网站不在它自己的网站的根目录中

例如:

http://intranet.mycompany.com/inform

这基本上是我的文件夹结构的根",所以我所有的文件夹都从那里开始(css 文件 default.cshtml... 等等)

当我从链接<a href="../linkOnParentLevel.cshtml">链接</a><a href="subFolder/linkOnOneLevelDown.cshtml">链接</a>

编辑 3

当使用Layout页面时,你可以使用Href扩展方法来生成一个相对的url:

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

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 ?

解决方案

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")" ...

这篇关于在 Razor 中使用站点根相关链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆