Using site root relative links in Razor

后端 未结 3 659
臣服心动
臣服心动 2020-12-08 06:30

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

相关标签:
3条回答
  • 2020-12-08 06:50

    I know that '~' is added by default, but I tend to change it so that all paths are relative to my code file rather than application root, using ".." eg. "../images/logos" etc

    0 讨论(0)
  • 2020-12-08 06:54

    Use Url.Content as shown bellow:

    <img src="@Url.Content("~/images/logos/hdr.png")" />
    
    0 讨论(0)
  • 2020-12-08 07:02

    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")" ...
    
    0 讨论(0)
提交回复
热议问题