ASP.NET MVC View not rendering script tags properl

2019-06-11 06:39发布

问题:

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.

回答1:

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


回答2:

Either stick the references in a bundle and use @Scripts.Render("~/bundlename") or use

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