简体   繁体   English

局部视图中的 ASP.net MVC javascript 未运行

[英]ASP.net MVC javascript in partial view is not running

Maybe someone that can help me to understand what is the problem or error with this call to a partial view that has its own javascript code.也许有人可以帮助我了解对具有自己的 javascript 代码的局部视图的调用存在什么问题或错误。

This is the main cshtml:这是主要的cshtml:

@model  Ads_Negocio.FormTest

@{
    ViewBag.Title = "Reportone";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div> <p>Parent view</p> </div>
<p>----------Partial view section-----------</p>
<div>
    <p>Partial view</p>
    @Html.Partial("Componente/_aTestView")
</div>

@section scripts{
    <script type="text/javascript">
        $(document).ready(function () {
            alert("parent view renderign")
        });
    </script>
}

the partial view _aTestView.cshtml:部分视图_aTestView.cshtml:

<button type="button" id="btnGraficNew">Run</button>

<script type="text/javascript">
    $(document).ready(function () {
        alert("partial view rendering");
        $("#btnGraficNew").click("click", function () {
            alert("Call from partial view");
        });
    });
</script>

Problems:问题:

  1. After view is rendereng alert inside partial view is never call.视图渲染后,局部视图内的警报永远不会调用。
  2. When I press botton, it does not alert.当我按下按钮时,它不会发出警报。

When you run your code you can see the below error in console window.当您运行代码时,您可以在控制台 window 中看到以下错误。

Uncaught ReferenceError: $ is not defined 

Solution - You should put the jquery reference in the head section of the _Layout.cshtml page.解决方案- 您应该将 jquery 引用放在 _Layout.cshtml 页面的 head 部分。 Once you do that your code will run as expected.一旦你这样做,你的代码将按预期运行。 If you are using default bundle then below code will work.如果您使用的是默认捆绑包,那么下面的代码将起作用。

<head>
    ...
    @Scripts.Render("~/bundles/jquery")
</head>

or或者

<head>
    ...
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>

Partial View is loaded together with the parent view.部分视图与父视图一起加载。 Therefore, the javascript command should be reside on the parent view rather than the partial view itself.因此,javascript 命令应该驻留在父视图而不是局部视图本身。

window.addEventListener works on partial views. window.addEventListener 适用于部分视图。

Put your code inside addeventlistener method.将您的代码放在 addeventlistener 方法中。

For example this code works in my partial views only with addEventListener.例如,此代码仅适用于 addEventListener 在我的部分视图中。

<script defer>
 window.addEventListener("load", function () {
    $(document).on("change", "#ddlBirim", function () {
        window.location.href = "/@controller/@action/" + $(this).val();
    });
 });
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM