C#在聊天脚本中将数据附加到DIV

本文关键字:DIV 数据 聊天 脚本 | 更新日期: 2023-09-27 18:19:58

我使用AJAX Timer在ASP.NET C#中创建了一个聊天应用程序,由于updatepanel的定期更新,我无法控制滚动条,也无法选择文本。现在,我想知道将从数据库接收的数据附加到DIV的替代方法是什么。使用C#和AJAX、jQuery或JavaScript,我如何将检索到的文本附加到DIW?

我的代码部分

while(dr.read())
{
   string chatvalues = dr[0].ToString();
   // How to append this chatvalues a DIV
}

C#在聊天脚本中将数据附加到DIV

如果您只想要纯文本,并且假设您的div的id为divChat并设置为runat="server",则可以执行以下操作:

var sbChatData = new System.Text.StringBuilder(1000);
while(dr.read())
{
   sbChatData.AppendLine(dr[0].ToString());
}
divChat.InnerText += sbChatData.ToString();

更新

除了张贴或使用更新面板之外,还有一种选择是使用ajax请求或静态页面方法来检索您想要在div中使用的值。

下面是一个使用页面方法的快速示例:

1) 如果你还没有,请在你的页面上添加一个脚本管理器:

<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" EnablePartialRendering="true" runat="server" />

2) 在你的页面上添加一个静态方法来获取聊天内容:

    [System.Web.Services.WebMethod]
    public static string GetChatData()
    {
        // Some additional code; you will probably also need to pass a paramter for the chat id
        var sbChatData = new System.Text.StringBuilder(1000);
        while (dr.read())
        {
            sbChatData.AppendLine(dr[0].ToString());
        }
        return sbChatData.ToString();
    }

3) 添加javascript获取聊天数据并更新div:

<script language="javascript" type="text/javascript">
    function UpdateChatData() {
        var sChatData = PageMethods.GetChatData();
        if (sChatData != null) {
            document.getElementById('divChat').innerText = sChatData;
        }
    }
</script>