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:
- After view is rendereng alert inside partial view is never call.
- When I press botton, it does not alert.
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:
- After view is rendereng alert inside partial view is never call.
- When I press botton, it does not alert.
3 Answers
Reset to default 3Partial View is loaded together with the parent view. Therefore, the javascript mand should be reside on the parent view rather than the partial view itself.
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./ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
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>