【问题标题】:$ reference is not defined$ 引用未定义
【发布时间】:2015-05-23 00:21:55
【问题描述】:

我知道这意味着 jquery 没有加载,但是我的代码似乎是正确的。

我的 _layouts.cshtml

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Application name", "Index", "Home", null, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("Property", "Property", "Home")</li>
                    <li>@Html.ActionLink("App Properties", "GetAzureAadApp", "ActiveDirectory")</li>
                    <li>@Html.ActionLink("Create App Properties", "CreateProperty", "ActiveDirectory")</li>
                    <li>@Html.ActionLink("Get Extended Properties", "GetProperties", "ActiveDirectory")</li> 
                    <li>@Html.ActionLink("CreateUser", "CreateUser", "ActiveDirectory")</li>     
                    <li>@Html.ActionLink("TestRestCall", "TestRestCall", "ActiveDirectory")</li>                   
                </ul>
                @Html.Partial("_LoginPartial")
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

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

我的看法

@model PruebasAD.Models.SuccessViewModel
@{
    ViewBag.Title = "TestRestCall";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>TestRestCall</h2>
<article>
  <aside class="green">
    @Model.Message
  </aside>
  <aside>
    <pre id="json-result">
    </pre>
  </aside>
</article>


<script type="text/javascript">
  $(document).ready(function(){
    var str = JSON.stringify(@(new MvcHtmlString(Model.JSON)), undefined, 2); // indentation level = 2
    $('#json-result').html(str);
    console.log(str);
  });
</script>

和我的控制器操作

public async Task<ActionResult> TestRestCall()
{
    Uri serviceRoot = new Uri(azureAdGraphApiEndPoint);
    var token = await GetAppTokenAsync();
    string requestUrl = "https://graph.windows.net/mysaasapp.onmicrosoft.com/users?api-version=2013-04-05";
    HttpClient hc = new HttpClient();
    hc.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
    HttpResponseMessage hrm = await hc.GetAsync(new Uri(requestUrl));
    if (hrm.IsSuccessStatusCode)
    {
        string jsonresult = await hrm.Content.ReadAsStringAsync();
        return View("TestRestCall", new SuccessViewModel
        {
            Name = "The Title",
            Message = "The message",
            JSON = jsonresult.ToJson()
        });
    }
    else
    {
        return View();
    }
}

【问题讨论】:

    标签: javascript jquery asp.net asp.net-mvc


    【解决方案1】:

    您不必像@CupawnTae 建议的那样将您的@Scripts 声明移动到&lt;head&gt;

    相反,您可以将视图中的脚本移动到脚本部分(在您的布局中配置。)

    @model PruebasAD.Models.SuccessViewModel
    @{
        ViewBag.Title = "TestRestCall";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    <h2>TestRestCall</h2>
    <article>
      <aside class="green">
        @Model.Message
      </aside>
      <aside>
        <pre id="json-result">
        </pre>
      </aside>
    </article>
    
    @section scripts{
    <script type="text/javascript">
      $(document).ready(function(){
        var str = JSON.stringify(@(new MvcHtmlString(Model.JSON)), undefined, 2); // indentation level = 2
        $('#json-result').html(str);
        console.log(str);
      });
    </script>
    }
    

    在您的布局中,由于您在 jQuery 参考下方呈现您的脚本部分,它们将按正确的顺序加载。

    这很重要的原因是它将在页面的主要 HTML 之后加载脚本。该页面感觉加载速度更快,因为用户会更快地看到该站点。这适用于 HTML 文档和 CSS 引用较小的网站。

    不过,您可能还对Where is the best place to put tags in HTML markup? 感兴趣,其中讨论了有关放置标签的更好做法。

    【讨论】:

      【解决方案2】:

      试着移动你的

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

      进入&lt;head&gt; 部分,以便在您尝试访问之前加载它。 Adding a defer attribute 将允许页面继续加载,而无需等待 jQuery 完成加载 (on supported browsers)。

      <head>
          <meta charset="utf-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <title>@ViewBag.Title - My ASP.NET Application</title>
          @Styles.Render("~/Content/css")
          @Scripts.Render("~/bundles/modernizr")
          @Scripts.RenderFormat("<script src='{0}' defer='defer'></script>","~/bundles/jquery")
      </head>
      

      【讨论】:

      • @mason 感谢您的建议。不幸的是,我对 Razor 的了解还不够,无法实现这一目标。谷歌搜索找到了这个答案——这仍然是最好的方法吗? stackoverflow.com/a/18001995/1469259
      • 是的,这对我来说是个不错的方法。哦,还有,你可能想使用(或提及)section 来完成此操作,因为 head 是在布局中定义的,并且将 jQuery 放入布局中意味着每个页面现在都将引用 jQuery,这可能或者可能不是 OP 想要的。
      • @mason 再次感谢,添加了defer,但我需要多阅读一些内容,然后才能说得通sections
      【解决方案3】:

      您的脚本在 JQuery 之上运行。在您在模板文件中加载 JQuery 的位置下方添加一个脚本部分。然后在视图中使用您的页面特定脚本填充该部分。这会将您的脚本放在 JQuery 下方,并将您的脚本放在底部以帮助缩短页面加载时间

      【讨论】:

        猜你喜欢
        • 2012-06-29
        • 2016-06-21
        • 2011-07-14
        • 2012-01-14
        • 2020-11-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多