Recently, I've wanted to have a javascript method trigger when a certain page loads in my ASP.NET MVC project. This sounds easy enough, but there were a few things that presented problems for me:
- I'm using a Master.Template, and this is the file with the <body> tag in which I would normally put the JavaScript call,
- Putting the call in the Master.Template will trigger the Javascript event on every view page, while I want it on only one specific view
- This view doesn't have a <body> tag and presents no obvious way of firing the javascript method.
After giving this some consideration and several failed attempts, I came up with a solution that worked quite well.
First, in your Master.Template, edit your <body> tag to the following:
<body onload="CheckForLoadEvent()">
In the head section of the Master.Template, add this code:
<script language="javascript" type="text/javascript">
function CheckForLoadEvent()
{
if(window.ExecuteOnLoad != null)
window.ExecuteOnLoad();
}
</script>
Finally, in the view that you want the event to fire, add the ExecuteOnLoad() method.
<script language="javascript" type="text/javascript">
function ExecuteOnLoad() {
alert("hi");
}
</script>
Of course, you will likely want more than just an alert to popup, but this demonstrates proof of concept. You can go to any view in your MVC project, and the event will not execute until you load a view with an ExecuteOnLoad() method inside it.