简体   繁体   中英

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.

This is the main 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:

<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.

Uncaught ReferenceError: $ is not defined 

Solution - You should put the jquery reference in the head section of the _Layout.cshtml page. 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.

window.addEventListener works on partial views.

Put your code inside addeventlistener method.

For example this code works in my partial views only with addEventListener.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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