Setting the Body's OnLoad attribute in an Asp.net MVC Master Page

121

Solution 1

I have been using the following pattern with my current MVC project and it seems to be working pretty good for my .js work thus far...

Within my Master Page I load up my standard script files that I want to be used in all of my content pages (things like jquery.js, global.js, jquery-plugins, .css files, etc.). I then define whatever events that are needed in my master page (onLoad, onSave, etc.). Each content page that I create will have it's own .js file associated with it and I load that script file within the content .aspx page. Any .js events that need to be implemented differently between content pages are handled within the individual content .js file. So basically my Master Page has a set of .js functions that my content page scripts will implement. Right now I just store those template .js function signatures in a file and copy and paste them into every new content.js file that I need to create. However, I'm thinking about building a code generator or tool that would spit these template signatures out for me in any new .js file I need created (if .js has some form of interface capability or inheritance features let me know).

So to recap:

MasterPage.Master Loads: jquery.js, global.js, plugins.js

ContentPage Loads: ContentPage.js

Global.js contains functions that the master page invokes that do not change between content pages along with any other global routine functions.

Each ContentPage.js implements it's own functions for the content page along with those functions the master page invokes that have different behavior.

Solution 2

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

Solution 3

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>
 
Share:
121
mkirzon
Author by

mkirzon

Updated on November 01, 2020

Comments

  • mkirzon
    mkirzon over 3 years

    I'm relatively new to javascript/jquery.

    I am trying to run a nested for loop which dynamically creates HTML content which I then append into a table in my body. The first 'for' loop pulls data from Parse, and creates an html table row script, which I then append to a table in html body. The nested 'for' loop should run for each item in the first loop, and create a table row element directly below.

    However, for some reason (and I see this when I debug), the first for loop completes before triggering the nested loop. Is there any obvious reason or syntax that is causing this?

    Thanks in advance!

    $(document).ready(function(){
            var currentUser = Parse.User.current();
            var htmlContent = "";
            if (currentUser) {
                console.log(currentUser.get("full_name"));
                $("#user").html(currentUser.get("full_name"));
    
                var QrUrl = Parse.Object.extend("qr_url");
                var qr_query = new Parse.Query(QrUrl);
                qr_query.equalTo("createdBy", currentUser);
                qr_query.include("createdBy");
                qr_query.ascending("createdAt")
    
                qr_query.find({
                    success: function(qrid_results) {
                        for (var i = 0; i < qrid_results.length; i++) { 
                            var qridentry = qrid_results[i];
                            htmlContent="<tr><td>"+qridentry.get("title")+"</td><td>"+"Created"+"</td><td>"+qridentry.createdAt+"</td><td>"+qridentry.get("createdBy").get("full_name")+"</td></tr>";
                            $('#trackingtable').append(htmlContent);
    
                            var QrLogger = Parse.Object.extend("qr_logger");
                            var qrlog_query = new Parse.Query(QrLogger);
                            qrlog_query.equalTo("qrid", qridentry);
                            qrlog_query.include("createdBy");
                            qrlog_query.include("qrid");
    
                            qrlog_query.find({
                                success: function(qrlog_results) {
                                    for (var j = 0; j < qrlog_results.length; j++) { 
                                        var qrlogentry = qrlog_results[j];
                                        try{
                                            var user_id = obj.get("createdBy").get("full_name");
                                            console.log(user_id);
                                        }
                                        catch(err){
                                            user_id="Unknown Scanner";
                                        }
                                        var dated = qrlogentry.updatedAt;
                                        htmlContent="<tr><td>"+qrlogentry.get("qrid").get("title")+"</td><td>"+"Scanned"+"</td><td>"+dated+"</td><td>"+user_id+"</td></tr>";
                                        $('#trackingtable').append(htmlContent);    
                                    }
                                }
                            });
                            //$('#trackingtable').dataTable({   });
                        }
                    }
                });
            }
        });
    
    • Flight Odyssey
      Flight Odyssey over 10 years
      qrlog_query.find appears to be an asynchronous function.
    • Pointy
      Pointy over 10 years
      You do not really have nested for loops here. You need to understand how asynchronous interfaces work.
    • mkirzon
      mkirzon over 10 years
      Is there really no way to restrict this all to work as synchronous functions?
  • mkirzon
    mkirzon over 10 years
    Thanks so much. Unfortunately, after hours trying to achieve this, I could not be more confused. I think I am more interested in implementing your first suggestion (chaining the deferred execution). Is this done via 'promises'? If so, can you please help with how this can be done in the for loops?
  • mkirzon
    mkirzon over 10 years
    Thank you! After a few days of breathing async functions, I finally figured it out :)