I have created an ASP.NET MVC partial view and I am calling it via the HTML.Action helper method:
@Html.Action("GetMyPartialView", "MyController", new { myParameter})
The partial view contains a control that needs some JavaScript to be called (a JavaScript library in an external JavaScript file). How can I call this JavaScript code from within my partial view.
I tried using the script element inside the partial view:
<script>
MyJavaScriptFunction();
</script>
This did not work. Probably the external JavaScript files (e.g. jQuery) have not been loaded at that time.
What is the recommended way to execute JavaScript code when a partial view has been rendered?
To call a partial view from another partial view, we follow the same approach as we follow when we call partial view from the content page. Let's take an example. This is the code of 1st partial view. Notice that in above partial view, we are calling another partial view named "_View2" that is created below.
In ASP.NET Core MVC, a controller's ViewResult is capable of returning either a view or a partial view. In Razor Pages, a PageModel can return a partial view represented as a PartialViewResult object. Referencing and rendering partial views is described in the Reference a partial view section.
Then, in the view page, after the document is ready, you can use JQuery to get the Selected value, if the selected value is not the first option ("0"), load the partial view to display the related content. If the answer is the right solution, please click "Accept Answer" and kindly upvote it.
You cannot use java script sections in partial views. They simply don't work. So keep the @section JavaScript in the main view in order to register scripts and then render the partial view
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With