在ASP.net MVC 2.0中使用Url.Content

时间:2010-10-12 07:41:49

标签: asp.net-mvc

我见过很多使用Url.Content引用javascript的例子,在MVC 2中形成MasterPages。

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

但是在运行时我失败了,

  

编译错误   描述:编译服务此请求所需的资源时发生错误。请查看以下特定错误详细信息并适当修改源代码。

编译器错误消息:CS0103:当前上下文中不存在名称“Url”。

我还没有找到声明Url名称空间的位置,是否应该使用其他程序集?

VS2010,IIS 7,ASP.net MVC 2.0

3 个答案:

答案 0 :(得分:8)

确保您的母版页继承System.Web.Mvc.ViewMasterPage

答案 1 :(得分:2)

亚历克斯,

尝试添加以下扩展方法,看看它是否为您提供了进一步的

public static partial class HtmlHelperExtensions
{
    public static string Script(this HtmlHelper html, string path)
    {
        var filePath = VirtualPathUtility.ToAbsolute(path);
        HttpContextBase context = html.ViewContext.HttpContext;
        // don't add the file if it's already there
        if (context.Items.Contains(filePath))
            return "";
        return "<script type=\"text/javascript\" src=\"" + filePath + "\"></script>";
    }
}

用法:

<%=Html.Script("~/Scripts/jquery-1.4.2.min.js")%>

我知道它不会直接回答你的问题,但会允许你移动fwd ......

答案 2 :(得分:1)

删除了编辑,因为单引号被视为字符文字,因此导致“文字中的字符太多”错误。最可能的原因仍然是拼写错误,恕我直言。

ORIGINAL POST(仍然是UrlHelper类):

Url.Content():这里的Url是一个帮助方法,有点像Html或Ajax助手。

在代码中,我相信它的类是:

System.Web.Mvc.UrlHelper

即命名空间是System.Web.Mvc。

因此,如果您真的使用上面详述的规范,那么您不能使用它是非常奇怪的。