Search code examples
cssasp.net-mvcrazor

Independent cshtml relative path resources not loading


I have an independent cshtml file that is not loading js, css, img, resource files.

By independent I mean a csthml that is not using the layout and is primarily HTML with a tiny bit of razor thrown in.

At the top of my page I nullify the use of the layout and then begin my HTML.

@model Nop.Web.Views.LandingPages.Models.HalfAppt
@{ 
   Layout = null;
 }

<!DOCTYPE html>
<html lang="en">
<head>
    <title>XYZ Page</title>
    <meta charset="utf-8">
    <meta name="format-detection" content="telephone=no"/>
    <link rel="icon" href="images/fb/favicon.ico" type="image/x-icon">
    <link href='https://fonts.googleapis.com/css?family=Raleway:400,700,800' rel='stylesheet' type='text/css'>

    <link rel="stylesheet" href="css/fb/grid.css">
    <link rel="stylesheet" href="css/fb/style.css">
    .....etc.....

Now specifically to the links if this were an html page...and I have made it one to test...the paths would resolve.

However the razor syntax is not working out for me. I have tried the following:

Absolute paths:

<link href="http://localhost:1234/views/landingpages/images/fb/favicon.ico">

All manner of relative paths like:

<link href="~/Views/LandingPages/images/fb/favicon.ico" >
<link href="images/fb/favicon.ico" >
<link href="/images/fb/favicon.ico" >
<link href="../../../../Views/LandingPages/images/fb/favicon.ico" >

Razor:

<link href="@Url.Content(~/Views/LandingPages/images/fb/favicon.ico)" >

Here is my folder structure:

enter image description here


Solution

  • The usual location for images, icons, css files etc is somewhere inside the /Content folder, which is created by default in projects generated from the MVC template. If necessary subfolders can be created there too.

    The /Views folder is special in MVC, and by default its contents are not accessible from the outside world. (The .cshtml files inside it are rendered through the Razor engine, not returned literally as they are).

    If you really want to ignore this standard, then see this question & answers. Still I would not recommend doing so, if only to keep the site maintainable and understandable for co-developers, now or in the future.