0

Hi I am having a problem where I have my Page_Load function is being called whenever the AJAX timer calls it's function. However I have stuff in my Page_Load function that I only want to be activated once, not every 5 sec (when the AJAX method is supposed to be called). How do I uncouple the Page_Load function from the AJAX function, ie only call Page_Load once?

Thanks

protected void Page_Load(object sender, EventArgs e)
{
    if (!ScriptManager.GetCurrent(this.Page).IsInAsyncPostBack)
    {
        SendButton.Click += new EventHandler(SendButton_Click);
        if (Request.QueryString["RecID"] != null)
            Session["receivinguserid"] = Request.QueryString["RecID"];
        else
            Response.Redirect("~/Home.aspx");
        UserCredential sendingUser = (UserCredential)Session["authenticatedUser"];
        UserCredential receivingUser = Global.Users.Find(m => m.UserID == Convert.ToInt32(Session["receivinguserid"]));
        Conversation currentConversation = new Conversation((int)sendingUser.UserID, (int)receivingUser.UserID);
        if (sendingUser.Conversations.Find(m => m.ReceivingUserID == receivingUser.UserID) == null)
        {
            Global.Users.Find(m => m.Name == (string)Session["authenticatedUsersUsername"]).Conversations.Add(new Conversation((int)((UserCredential)Session["authenticatedUser"]).UserID, Convert.ToInt32(Session["receivinguserid"])));
            Global.Users.Find(m => m.UserID == Convert.ToInt32(Session["receivinguserid"])).Conversations.Add(new Conversation(Convert.ToInt32(Session["receivinguserid"]), (int)((UserCredential)Session["authenticatedUser"]).UserID));
        }
        else
        {
            currentConversation = sendingUser.Conversations.Find(m => m.ReceivingUserID == receivingUser.UserID);
            foreach (Message m in currentConversation.ReadMessageList)
            {
                if (m.UserID == sendingUser.UserID)
                {
                    ChatLabel.Text += "<br> " + sendingUser.Name.ToString() + ": " + m.MessageText + " " + m.MessageDate.ToString("dddd, dd MMMM HH:mm");
                }
                else if (m.UserID == receivingUser.UserID)
                {
                    ChatLabel.Text += "<br>" + receivingUser.Name.ToString() + ": " + m.MessageText + " " + m.MessageDate.ToString("dddd, dd MMMM HH:mm");
                }
            }
            foreach (Message m in sendingUser.Conversations.Find(m => m.ReceivingUserID == receivingUser.UserID).UnReadMessageList)
            {
                ChatLabel.Text += "<br>" + receivingUser.Name.ToString() + ": " + m.MessageText + " " + m.MessageDate.ToString("dddd, dd MMMM HH:mm");
                sendingUser.Conversations.Find(t => t.ReceivingUserID == receivingUser.UserID).ReadMessageList.Add(m);
            }
            sendingUser.Conversations.Find(m => m.ReceivingUserID == receivingUser.UserID).UnReadMessageList.Clear();
        }
    }
}

Here is the AJAX function:

public void UpdateChat(object sender, EventArgs e)
{
    UserCredential sendingUser = (UserCredential)Session["authenticatedUser"];
    UserCredential receivingUser = Global.Users.Find(m => m.UserID == Convert.ToInt32(Session["receivinguserid"]));
    foreach (Message m in sendingUser.Conversations.Find(c => c.ReceivingUserID == receivingUser.UserID).UnReadMessageList)
    {
        ChatLabel.Text += "<br>" + receivingUser.Name.ToString() + ": " + m.MessageText + " " + m.MessageDate.ToString("ddd, dd MMMM HH:mm");
        Global.Users.Find(u => u.UserID == (int)sendingUser.UserID).Conversations.Find(t => t.ReceivingUserID == receivingUser.UserID).ReadMessageList.Add(m);
    }
    Global.Users.Find(m => m.UserID == (int)sendingUser.UserID).Conversations.Find(t => t.ReceivingUserID == receivingUser.UserID).UnReadMessageList.Clear();
}

And here is the ScriptManager:

<a>
  <asp:ScriptManager ID="ScriptManager1" runat="server">
  </asp:ScriptManager>
   <asp:Timer ID="Timer1" OnTick="UpdateChat" Interval="5000" runat="server">
   </asp:Timer>
</a>

I added in Update Panels, which seems to catch most of the AJAX calls, but every once in a while my code under if(!ScriptManager.GetCurrent(this.Page).IsInAsyncPostBack) seems to run. Here is my code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Chat : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        {
            SendButton.Click += new EventHandler(SendButton_Click);
            if (Request.QueryString["RecID"] != null)
                Session["receivinguserid"] = Request.QueryString["RecID"];
            else
                Response.Redirect("~/Home.aspx");
            UserCredential sendingUser = (UserCredential)Session["authenticatedUser"];
            UserCredential receivingUser = Global.Users.Find(m => m.UserID == Convert.ToInt32(Session["receivinguserid"]));
            Conversation currentConversation = new Conversation((int)sendingUser.UserID, (int)receivingUser.UserID);
            if (sendingUser.Conversations.Find(m => m.ReceivingUserID == receivingUser.UserID) == null)
            {
                Global.Users.Find(m => m.Name == (string)Session["authenticatedUsersUsername"]).Conversations.Add(new Conversation((int)((UserCredential)Session["authenticatedUser"]).UserID, Convert.ToInt32(Session["receivinguserid"])));
                Global.Users.Find(m => m.UserID == Convert.ToInt32(Session["receivinguserid"])).Conversations.Add(new Conversation(Convert.ToInt32(Session["receivinguserid"]), (int)((UserCredential)Session["authenticatedUser"]).UserID));
            }
            else
            {
                currentConversation = sendingUser.Conversations.Find(m => m.ReceivingUserID == receivingUser.UserID);
                foreach (Message m in currentConversation.ReadMessageList)
                {
                    if (m.UserID == sendingUser.UserID)
                    {
                        ChatLabel.Text += "<br> " + sendingUser.Name.ToString() + ": " + m.MessageText + " " + m.MessageDate.ToString("dddd, dd MMMM HH:mm");
                    }
                    else if (m.UserID == receivingUser.UserID)
                    {
                        ChatLabel.Text += "<br>" + receivingUser.Name.ToString() + ": " + m.MessageText + " " + m.MessageDate.ToString("dddd, dd MMMM HH:mm");
                    }
                }
                foreach (Message m in sendingUser.Conversations.Find(m => m.ReceivingUserID == receivingUser.UserID).UnReadMessageList)
                {
                    ChatLabel.Text += "<br>" + receivingUser.Name.ToString() + ": " + m.MessageText + " " + m.MessageDate.ToString("dddd, dd MMMM HH:mm");
                    sendingUser.Conversations.Find(t => t.ReceivingUserID == receivingUser.UserID).ReadMessageList.Add(m);
                }
                sendingUser.Conversations.Find(m => m.ReceivingUserID == receivingUser.UserID).UnReadMessageList.Clear();
            }
        }
    }
    public void SendButton_Click(Object sender, EventArgs e)
    {
        UserCredential sendingUser = (UserCredential)Session["authenticatedUser"];
        UserCredential receivingUser = Global.Users.Find(m => m.UserID == Convert.ToInt32(Session["receivinguserid"]));
        Global.Users.Find(m => m.UserID == (int)sendingUser.UserID).Conversations.Find(t => t.ReceivingUserID == receivingUser.UserID).ReadMessageList.Add(new Message(MessageTextBox.Text, (int)sendingUser.UserID, DateTime.Now));
        Global.Users.Find(m => m.UserID == (int)receivingUser.UserID).Conversations.Find(t => t.ReceivingUserID == sendingUser.UserID).UnReadMessageList.Add(new Message(MessageTextBox.Text, (int)sendingUser.UserID, DateTime.Now));
        ChatLabel.Text += "<br>" + sendingUser.Name.ToString() + ": " + MessageTextBox.Text + " " + DateTime.Now.ToString("ddd, dd MMMM HH:mm");
        MessageTextBox.Text = String.Empty;
    }
    public void UpdateChat(object sender, EventArgs e)
    {
        UserCredential sendingUser = (UserCredential)Session["authenticatedUser"];
        UserCredential receivingUser = Global.Users.Find(m => m.UserID == Convert.ToInt32(Session["receivinguserid"]));
        foreach (Message m in sendingUser.Conversations.Find(c => c.ReceivingUserID == receivingUser.UserID).UnReadMessageList)
        {
            ChatLabel.Text += "<br>" + receivingUser.Name.ToString() + ": " + m.MessageText + " " + m.MessageDate.ToString("ddd, dd MMMM HH:mm");
            Global.Users.Find(u => u.UserID == (int)sendingUser.UserID).Conversations.Find(t => t.ReceivingUserID == receivingUser.UserID).ReadMessageList.Add(m);
        }
        Global.Users.Find(m => m.UserID == (int)sendingUser.UserID).Conversations.Find(t => t.ReceivingUserID == receivingUser.UserID).UnReadMessageList.Clear();
    }
}

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Chat.aspx.cs" Inherits="Chat" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
  <a>
  <asp:ScriptManager ID="ScriptManager1" runat="server">
  </asp:ScriptManager>
   <asp:Timer ID="Timer1" runat="server">
   </asp:Timer>
  </a>
  <asp:UpdatePanel runat="server">
   <Triggers>
    <asp:AsyncPostBackTrigger ControlID="tim" EventName="Tick" />
   </Triggers>
   <ContentTemplate>
    <asp:Timer ID="tim" Interval="5000" Enabled="true" OnTick="UpdateChat" runat="server"></asp:Timer>
    <asp:Label ID="ChatLabel" runat="server"></asp:Label>
   </ContentTemplate>
  </asp:UpdatePanel>
  <asp:TextBox ID="MessageTextBox" runat="server"></asp:TextBox>
  <asp:Button ID="SendButton" runat="server" Text="Send" />
    </div>
    </form>
</body>
</html>
Xigaphactus
  • 37
  • 1
  • 6

1 Answers1

1

If you're using a Scriptmanager you can try this. add code to Page_Load.

 if (ScriptManager.GetCurrent(this.Page).IsInAsyncPostBack)
        {
            // partial (asynchronous) postback occured
            // insert Ajax custom logic here
        }
        else
        {
            // regular full page postback occured
            // custom logic accordingly                
        }

Found this from : https://forums.asp.net/t/1562871.aspx?Can+we+check+partial+postback+

Pintang
  • 438
  • 4
  • 17
  • Tried that (see code I attached above) and I'm still having this problem. – Xigaphactus Aug 22 '17 at 17:16
  • Looking at just your code, all of your code is in the if statement that fires when it is an Ajax post back. Is that the code you want to fire during Ajax postback? I don't see and else statement to that for the code that you don't want to fire during Ajax postback – Pintang Aug 22 '17 at 17:20
  • According to your post if ScriptManager.GetCurrent(this.Page).IsInAsyncPostBack == true, the AJAX logic will fire. The code I have above fires when this is NOT TRUE (perhaps you missed the "!" mark in front of the statement). – Xigaphactus Aug 22 '17 at 17:52
  • I did miss the "!". My apologizes. This is correct. Do you have any unwanted AutoPostBack=true tags that your ajax might touch? – Pintang Aug 22 '17 at 18:11
  • I provided the code for the function that the AJAX calls and the Scriptmanager itself (which is basically the entire code for the page). Tell me if you see anything fishy. – Xigaphactus Aug 22 '17 at 18:24
  • I believe your problem lies in your OnTick call. This is going to call to the server with will inevitably cause a postback. I'm thinking you're going to need to Use an UpdatePanel and ajaxtriggers to target only what you want to postback. Check this link out for similar issue: https://stackoverflow.com/questions/9063045/avoid-post-back-while-doing-a-timer-tick-function – Pintang Aug 22 '17 at 18:51
  • Okay I updated my code and the if(!ScriptManager.GetCurrent(this.Page).IsInAsyncPostBack) seems to be catching the partial refreshes now, but every once in awhile this statement seems to come back as true and the logic that I only want to run when the page initially loads still runs. I posted my new code above, if you see anything fishy let me know. – Xigaphactus Aug 26 '17 at 16:11