如何在ASP.NET MVC4视图页面中包含JavaScript代码?

4

我是ASP.NET MVC4架构的新手,以下是我遇到的问题,请帮助我。

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryui")

<script type="text/javascript">
$(function () {
    $("#sections").tabs();
    //here i am getting error that Object[object object] has not method tabs    
});
</script>

<div id="sections">
    <ul>
        <li><a href="#section-1">section-1 </a></li>
        <li><a href="#section-2">section-2 </a></li>
    </ul>
        <div id="section-1">
        section-1 content............  
        </div>
        <div id="section-2">
        section-2 content............ 
        </div>
    </div>

感谢您的提前帮助......
1个回答

10

你可能已经包含了 ~/bundles/jquery 两次。检查一下你的 ~/Views/Shared/_Layout.cshtml 文件。最后你可能有以下代码:

    @Scripts.Render("~/bundles/jquery")
    @RenderSection("scripts", required: false)
</body>

因此,jQuery包已经包含在您的页面中。您不应该在视图中再次包含它。您只需要使用~/bundles/jqueryui包:

@Scripts.Render("~/bundles/jqueryui")

<script type="text/javascript">
$(function () {
    $("#sections").tabs();
    //here i am getting error that Object[object object] has not method tabs    
});
</script>

<div id="sections">
    <ul>
        <li><a href="#section-1">section-1 </a></li>
        <li><a href="#section-2">section-2 </a></li>
    </ul>
    <div id="section-1">
        section-1 content............  
    </div>
    <div id="section-2">
        section-2 content............ 
    </div>
</div>

更新:

下面是一个完整的例子,展示你的视图结构可能会是怎样的:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Foo</title>
    <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" />
</head>
<body>
    <div id="sections">
        <ul>
            <li><a href="#section-1">section-1 </a></li>
            <li><a href="#section-2">section-2 </a></li>
        </ul>
        <div id="section-1">
            section-1 content............  
        </div>
        <div id="section-2">
            section-2 content............ 
        </div>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryui")
    <script type="text/javascript">
        $("#sections").tabs();
    </script>
</body>
</html>

谢谢回复...但是当我删除@Scripts.Render("~/bundles/jqueryui")这一行时,它会显示$未定义... - savy
1
你不应该删除 @Scripts.Render("~/bundles/jqueryui") 这一行。如果在 _Layout.cshtml 中已经存在 @Scripts.Render("~/bundles/jquery") 这一行,则应将其删除。这种情况是否存在?我已经更新了我的答案,并附上了一个示例,展示您的视图可能是什么样子。 - Darin Dimitrov
如果您不使用bundler(或任何其他缩小工具),您该如何做到这一点?我得到了与OP相同的行为。它包含在_Layout中,但是我还必须在每个要在其中使用JavaScript的页面中包含它。否则我会得到未定义的$。 - Rex Whitten

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接