I have a view using a master page that contains some javascript that needs to be executed using the OnLoad of the Body. What is the best way to set the OnLoad on my MasterPage only for certain views?
On idea I tried was to pass the name of the javascript function as ViewData. But I dont really want my Controllers to have to know about the javascript on the page. I really don't like this approach...
<body onload="<%=ViewData["Body_OnLoad"]%>">
<asp:ContentPlaceHolder ID="MainContent" runat="server" />
Edit - I suppose one idea would be to use jQuery's document ready event instead...
Any other ideas?
Solution from Blog: Using body onload with ASP.net 2.0 MasterPages
MasterPage.master
<head>
<asp:ContentPlaceHolder runat="server" id="Headers">
</asp:ContentPlaceHolder>
<script language=javascript>
function mp_onload() {
if(window.body_onload != null)
window.body_onload();
}
</script>
</head>
<body onload="mp_onload();">
Default.aspx
<asp:Content ID="Content2" ContentPlaceHolderID="Headers" Runat="Server">
<script language="javascript">
function body_onload()
{
//do something
}
</script>
</asp:Content>
Now that JQuery is officially part of ASP.NET MVC, I would recommend using it. It's small, and adds tons of value to your application.
I would recommend adding Mustafa's version of JQuery that has the Intellisense comments included:
jquery-1.2.6-intellisense.js
Then add it to your Scripts folder (new in MVC Beta 1), and reference it like this:
<script language="javascript" type="text/javascript" src="../../Scripts/jquery-1.2.6-intellisense.js"></script>
In your code you can now add a function like this:
$(document).ready(function() {
// do stuff when DOM is ready
});
Since you mentioned that you only want it to happen in certain views, you could add a placeholder in your Master Page like this:
<asp:contentplaceholder id="JavascriptPlaceholder" runat="server"></asp:contentplaceholder>
Then in your View, you could choose to put code in there, or not.
which would go inside of the head section
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