我使用 AJAX 计时器在 ASP.NET C# 中创建了一个聊天应用程序,由于 updatepanel
的定期更新,我无法控制滚动条并且无法选择文本。现在,我想要将从数据库接收到的数据附加到 DIV 的替代方法是什么。将 C# 与 AJAX、jQuery 或 JavaScript 结合使用,如何将检索到的文本附加到 DIV?
我的部分代码
while(dr.read())
{
string chatvalues = dr[0].ToString();
// How to append this chatvalues a DIV
}
最佳答案
如果你只想要纯文本,假设你的 div 有一个 divChat 的 id 并且设置为 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>
关于C#在聊天脚本中将数据附加到DIV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8824661/