当前位置: 动力学知识库 > 问答 > 编程问答 >

routing - In ASP.NET MVC, adding a script reference throws exception

问题描述:

On a skeleton ASP.MVC that Visual Studio creates, I add a script tag to my head section in Site.Master:

<script src="~/Scripts/jquery-1.3.2.js" type="text/javascript"></script>

This causes the page to not render. In my case, I had a custom controllerfactory and the base method GetControllerInstance threw an exception:

The controller for path

'/~/Scripts/jquery-1.3.2.js' could not

be found or it does not implement

IController.

Using "../../Scripts/jquery-1.3.2.js" for the src does not work either.

The only way it works is:

<script src="<%= Url.Content("~/Scripts/jquery-1.3.2.js") %>"

type="text/javascript"></script>

Then of course, the intellisense does not work for jquery. So I have to resort to adding the hack:

<% if (false) { %>

<script src="~/Scripts/jquery-1.3.2.js" type="text/javascript"></script>

<% } %>

which the hotfix was supposed to fix according to ScottGu

A line above is a link to a stylesheet:

<link href="~/Content/Site.css" rel="stylesheet" type="text/css" />

For some reason, that works fine. Whether I use the virtual or relative path, I can see that the resulting url on the page is "Content/Site.css". The same can't be said for the jquery url. jquery link is returned as is - the jquery url is returned on the page containing the "~" or the "../..".

Can someone tell me what is going on?

Thanks

UPDATE:

Thanks to the commenters, I remembered that ~ is an asp.net thing. My only question is then why doesn't the same issue exist for the stylesheet? The link tag above, for example, I can put ~ or relative paths and it always comes out right. Where is the magic?

网友答案:

Have you tried without the ~:

<script src="/Scripts/jquery-1.3.2.js" type="text/javascript"></script>

The ~ character is used only by server side processing scripts indicating the root of the web site. The reason:

<script src="<%= Url.Content("~/Scripts/jquery-1.3.2.js") %>" type="text/javascript"></script>

works is because it is translated to:

<script src="/Scripts/jquery-1.3.2.js" type="text/javascript"></script>
网友答案:

The "~" is not supported within standard HTML - it is an ASP.NET shortcut. So you've either got to do it the way you specified in your OP and the hack for intellisense, or as Darin specified but then you lose the ability to automatically pick up your VRoot.

网友答案:

I don't know for sure, but maybe MVC is smart enough to not include CSS files in the routing.

分享给朋友:
您可能感兴趣的文章:
随机阅读: