You want to render a script specific for your partial view only (usually after an ajax call), however the script is dependent on another script being loaded - like JQuery - and sadly, you are not using javascript modules.
Partial Views in ASP.NET MVC do not support section areas
@section scripts{
//not supported in Partial Views :(
}
public static firePartialViewEvent(): void
{
/*
* longer way of writing is to maintain IE compatibility
* https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events
*
*/
const loadEvent = document.createEvent('Event');
loadEvent.initEvent('finished:loading', true, true);
document.querySelector('body').dispatchEvent(loadEvent);
}
/**
* Call this from the partial view's script, if doing an ajax request
* @param script the partial view script to call
*/
public static loadPartialViewScript(script: () => void): void
{
const body = document.querySelector('body');
const options: AddEventListenerOptions = {
once: true,
}
body.addEventListener('finished:loading', () =>
{
script();
}, options);
}
//in your JavaScript/TypeScript file's ajax call
$.get(<blah blah>).done(() => firePartialViewEvent());
//in your Partial View
@if (Request.IsAjaxRequest()) // you usually only want to call this in an ajax request where the main view is ideally not returned
{
<script>
(() =>
{
loadPartialViewScript(() => <your partial view script>);
})();
</script>
}
//and in your main view you have the usual @section scripts that will render the needed scripts of the Partial View (duplicate call)
<script defer>
in the Partial View//on a JS file somewhere (i.e partial-view-caller.js)
(() => <your partial view script>)();
//in your Partial View
<script src="~/partial-view-caller.js" defer></script>
//you can actually just straight call your partial view script living in an external file - I just prefer having an initialization method :)
I personally prefer Workaround Two for its simplicity. However, I implemented Workaround One first - cause I’m an idiot who didn’t know how to properly use defer :D
However, Workaround One is in my opinion the ideal way in case you want to pass some data from your C# ViewModel to that Partial View script, which is also a common scenario. Therefore, both methods are useful - it depends on your situation.