简体   繁体   中英

ASP.NET Page_Load vs. AJAX page refresh code re-use / Redundancy?

Below is a working sample of code however I often find myself writing Page_Load content only to find myself re-writing the same sort of code doing the same sorts of things on the page after loading via ajax (to avoid the postback)....

I can't help but think there must be some sort of better (maybe object oriented) way to manipulate and create the dynamic HTML methods we need to maintain after an initial .NET page load without refreshing the entire page.

In the code sample below you can assume that the AjaxEnginePage is an existing .NET page that appropriately parses query strings and also that GetRealTimeFavoritesList() returns an appropriate list of objects with all information needed to be parsed in C# or JavaScript, from that point back, we GET code re-usability, but how do we get it in C# / JS?

OnlineMemberList.ascx

 <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="OnlineMemberList.ascx.cs"        Inherits="OnlineMemberList" %>
 <script src="../AJAJSON/Favorites/Favorites.js"></script>
 <script src="../AJAJSON/Jquery/jquery-1.9.1.js"></script>
 <script src="../AJAJSON/Jquery/jquery-ui-1.10.2.custom.js"></script>
 <script src="../AJAJSON/Jquery/jquery.mousewheel.js"></script>
 <script src="../AJAJSON/Jquery/jquery.jscrollpane.js"></script>
 <script type="text/javascript">
      $(document).ready(function () {
         var settings = {
                           autoReinitialise: true
                        };

      $('.scroll-pane').jScrollPane(settings);

      setInterval(function () {
        UpdateFavoritesList();
        }, 10000);
     });
 </script>

<div id="FavoritesList">
    <h3>Favorites</h3>
    <div id="BottomBorderFavorites"></div>
    <div id="Favorites" class="scroll-pane">
      <br />
      <p style="text-align: center;">--- Online ---</p>
      <div id="OnlineFavoritesUserNames" class="OnlineFavoritesUserNames" runat="server"></div>
      <div id="FavoritesChatIcon" class="FavoritesChatIcon" runat="server"></div>
      <div style="clear: both;"></div>
      <br />
      <p style="text-align: center;">--- Offline ---</p>
    <div id="OfflineFavoritesUserNames" class="OfflineFavoritesUserNames" runat="server"></div>
</div>

OnlineMemberList.ascx.cs

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            List<FavoriteSummary> summaries = favoritesBLL.GetRealTimeFavoritesList();
            foreach (FavoriteSummary summary in summaries)
            {

                if (summary.isOnline)
                {
                    OnlineFavoritesUserNames.InnerHtml += "<p>" + summary.you.UserName + "</p>";
                    if (summary.isAvailableForIM)
                        FavoritesChatIcon.InnerHtml += "<p><img src='../Images/FavoritesList/send-message.png' onclick=\"NewIMWindow('" + summary.you.UserName + "')\"; style='width: 15px; height: 13px;'></img></p>";
                    else
                        FavoritesChatIcon.InnerHtml += "<p></p>";
                }
                else
                {
                    OfflineFavoritesUserNames.InnerHtml += "<p>" + summary.you.UserName + "</p>";
                }
            }
        }
    }

Favorites.js

function UpdateFavoritesList() {

var url = AjaxEnginePage + Category  + "&Action=GetRealTimeFavoritesList";
$.getJSON(url, null, function (results) {
    UpdateFavoritesListDisplay(results)
});


function UpdateFavoritesListDisplay(favoritesArray) {
$(".OnlineFavoritesUserNames")[0].innerHTML = "";
$(".FavoritesChatIcon")[0].innerHTML = "";
$(".OfflineFavoritesUserNames")[0].innerHTML = "";

if (favoritesArray["FavoriteSummary"].length !== 0) {
    for (var i = 0; i < favoritesArray["FavoriteSummary"].length; ++i) {
        if (favoritesArray["FavoriteSummary"][i].isOnline == "True") {
            $(".OnlineFavoritesUserNames")[0].innerHTML += "<p>" + favoritesArray["FavoriteSummary"][i].yourUserName + "</p>";
            if (favoritesArray["FavoriteSummary"][i].isAvailableForIM == "True") {
                $(".FavoritesChatIcon")[0].innerHTML += "<p><img src='../Images/FavoritesList/send-message.png' class='FavoritesChatIcon' onclick=\"NewIMWindow('" + favoritesArray["FavoriteSummary"][i].yourUserName + "')\" /></a></p>";
            }
            else {
                $(".FavoritesChatIcon")[0].innerHTML += "<p></p>";
            }
        }
        else {
            $(".OfflineFavoritesUserNames")[0].innerHTML += "<p>" + favoritesArray["FavoriteSummary"][i].yourUserName + "</p>";
        }
    }
}
else {
    $(".OnlineFavoritesUserNames")[0].innerHTML += "<p>No Favorites</p>";
}
}
}     

You don't need to generate this markup on the server side at all. You already have a working ajax call that will fetch the data and generate the markup in javascript. So you should call that when the pages loads, as well as every 10 seconds. Ie:

UpdateFavoritesList();  
setInterval(function () {
    UpdateFavoritesList();
    }, 10000); 

This way when the page loads, you immediately run an ajax call and populate your markup and you can remove all the duplicate code from the Page_Load method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM