Search code examples
asp.net-mvcasp.net-mvc-4razorrazor-2

ASP.NET MVC View not rendering script tags properly


I have a very simple MVC project, and in my _Layout.cshtml I have some js includes like so:

<script src="~/scripts/jquery-2.0.3.min.js"></script>
<script src="~/scripts/easing.js"></script>
<script src="~/scripts/bootstrap.js"></script>

However, when it renders, it renders on the page like (note the tilde on the first one):

<script src="~/scripts/jquery-2.0.3.min.js"></script>
<script src="/scripts/easing.js"></script>
<script src="/scripts/bootstrap.js"></script>

I can't seem to get it to render properly, and it doesn't matter which script tag is first, that's the one it adds/keeps the tilde on. I've resorted to including the jquery script twice, the first one will have a tilde but the second one will get included, but I don't like that solution at all.

I'm working with VS 2012, it's a .NET 4.5 MVC application. From my searches it seems this was a known issue for Razor v1, but the solutions they provide don't seem to apply here.


Solution

  • You should be using @Url.Content() helper (We're not in ASP.NET any more, toto).

    <script src="@Url.Content("~/Scripts/jquery-2.0.3.min.js")"></script>
    <!-- etc. -->
    

    Another option is to use the Microsoft.AspNet.Web.Optimization package and create bundles:

    **BundleConfig.cs

    public void RegisterBundles(BundleCollection bundles)
    {
      // ...
      bundles.Add(new ScriptBundle("~/js/site").Include(
        "~/Scripts/jquery-2.0.3.min.js",
        "~/Scripts/easing.js",
        "~/Scripts/bootstrap.js"
      ));
      // ...
    }
    

    Then in your page use:

    @Scripts.Render("~/js/site")