The ASP.net MVC partial view is experiencing issues with running JavaScript code

Can anyone help me understand what's causing an issue with this call to a partial view that has its own JavaScript code?

This is the main cshtml file:

@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 rendering")
        });
    </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>

Issues:

  1. The alert inside the partial view is never triggered after the view is rendered.
  2. When pressing the button, no alert is displayed.

Answer №1

When loading a Partial View, it is important to remember that the javascript commands should be placed in the parent view, not within the partial view.

Answer №2

Upon running your code, you may encounter the following error message in the console window.

Uncaught ReferenceError: $ is not defined 

Solution: To resolve this issue, ensure that you include the jQuery reference in the head section of the _Layout.cshtml page. This will allow your code to execute correctly. If you are using the default bundle, the following code snippet should work:

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

Alternatively, you can use the following script tag to include jQuery from a CDN:

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

Answer №3

Utilizing window.addEventListener is crucial for functionality in partial views.

Ensure your code is encapsulated within the addEventListener method to guarantee proper execution.

An example showcasing this necessity is demonstrated below, exclusively functioning with addEventListener in my partial views:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling with handling numbers and special symbols in the Letter Changes problem on Coderbyte

Hello I have been struggling to find a solution for my current issue. The problem lies within an exercise that requires changing only alphabetical characters, but test cases also include numbers and special characters which are being altered unintentionall ...

Guide to creating the shared section of two wheels with CanvasRenderingContext2D

Is it possible to dynamically draw the shared area of two circular shapes using JavaScript and CanvasRenderingContext2D? My ultimate goal is to be able to adjust the size of the shape, ranging from a complete circle to a mere point. The desired outcome is ...

Having trouble running the npm run build command with vue-cli for production builds

Anticipated Outcome Executing npm run build should generate the production-ready dist bundle that can be deployed on a specified device. Current Scenario Despite successful local builds, encountering errors when attempting to execute npm run build on an ...

What is the best way to display a JavaScript object array on the screen

As someone who is new to JavaScript, I have a JavaScript object array that I would like to print the values of in the browser. However, I am unsure of how to do this without using document.write(vehicle); var vehicle = [{name:'Van',wheel:4,cha ...

NPM: Implementing a "post-install" hook that is only executed internally and not for package consumers

Currently, I am in the process of developing an NPM module and would like to automate certain tasks following every npm install while working on the module locally. However, it is crucial that these tasks are not executed when users of my library perform ...

Error in Blinking Tooltip when Hovering Skill Bubble (React and d3)

I've encountered a frustrating issue with tooltips on my website - they just won't stop blinking when I hover over the skill bubbles. I tried fixing the tooltips at a certain location, but whenever there's a bubble in that spot and I hover o ...

Creating a pluggable application in Node.js: A step-by-step guide

I am embarking on creating a Node.js and Express CMS with the following folder structure: MyCMS plugins themes uploads index.js I aim to load plugins from the plugins folder: plugins sample-plugin awesome-plugin ...

Mastering the art of counting down using a forEach loop in JavaScript

Trying to iterate through a list of objects, I can't index it, but can use forEach. My issue is I need to start from the last object and go to the first, but unsure how to achieve that with the forEach function. If I used a for loop, it would be like ...

Validation of multiple textboxes can be achieved by utilizing either JavaScript or Angular 1

How can I implement a validation in Angular 1 or JavaScript that will enable the submit button only when there is text in any of the 3 textboxes? If no text is present, the button should be disabled. Below is the code snippet: First name: <br> < ...

In Vue, using the ref function does not automatically result in the creation of a

CustomPage.vue: <template> <div> <CustomChild :cat = "this.parentCat" /> <div v-on:click="this.changeName" id="change-button"> Change Parent Cat name </div> </div> ...

Establish an angular scope within the DOM element

I am facing a challenge in creating a new Angular scope and attaching it to a DOM element. The situation is complicated by the fact that I am working on modifying a third-party control and cannot simply use a directive. My approach so far has been: ... = ...

Using JavaScript to compare arrays in order to display only the distinct outcome

Just starting out with JavaScript array matching! I've got two arrays, both with 11 elements each: txtfilename=['txt1','txt6','txt6','txt6','txt7','txt7','txt8','txt9',& ...

What could be the reason for receiving the error message "Unresolved variable or type approvedPriceDealerCostForm" in my HTML

I'm working with Angular 8 and facing an issue with sending the approvedPriceDealerCostForm when clicking my button. I keep getting an error that says "Unresolved variable or type approvedPriceDealerCostForm". Please refer to the attached image for mo ...

AngularJS: Enhancing User Experience by Preserving View State and Setup through Routes

Is it possible in a single page application to switch back and forth between AngularJS routes while maintaining the same state? Traditionally, this would involve binding data in a parent scope. However, for views with extensive graphical elements, this me ...

Algorithm to identify the highest sum of two numbers in a disorganized array of whole numbers

I am looking to create a function that can identify the largest pair sum in an unordered sequence of numbers. largestPairSum([10, 14, 2, 23, 19]) --> 42 (sum of 23 and 19) largestPairSum([99, 2, 2, 23, 19]) --> 122 (sum of 99 and 23) largestPairSum ...

Utilizing Visuals from a Vue Component Collection

As I attempt to publish a Vue library to npmjs, I encounter an issue with the images within it. After publishing the app to NPM and importing it into my main app, everything appears to be working correctly. However, the paths to the images in the library ...

In order to retrieve the latitude and longitude of a specific address using arcGis JavaScript, follow these

Hello, I'm wondering how to obtain the Latitude and Longitude using arcgis JavaScript. Can anyone help me with this? ...

Developing API requests depending on the input provided by users in a search field

Greetings everyone, I have a question that deals more with logic than code. I am currently working on an app where users can filter through various job types and access information about each role. While I have all the data stored in a database, I want us ...

React Native - useEffect causing a double render on Home screen

I am facing an issue where my functional component "Home" keeps rendering again after I receive data from a function in the "useEffect" hook. If I use the "set" statement to store the data from the function in a const, it triggers a re-render of the Home c ...

Unlimited scrolling feature implemented in a specified container using AngularJS

Does anyone have experience with using angularjs infinite scroll within an inner DIV instead of just the browser window? I'm trying to implement infinite scroll within a specific content wrapper that has its own scrollbar. The main page is fixed and ...