Search code examples
javascriptasp.net-mvcpartial-views

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.

Solution

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