提问人:Prabesh 提问时间:7/18/2016 更新时间:7/18/2016 访问量:818
如何使用 HttpContext 在 div 中包含文本?
How to include text inside div using HttpContext?
问:
我使用 HtmlGenericControl 在我的网页中包含了一个 div。 单击按钮,我想使用 HttpContext 在 div 中添加文本。我不想使用 InnerHtml,因为当我想包含的文本很长时,浏览器会挂起。 我尝试了以下方式,但它在 div 之外打印了文本。 请帮忙。 谢谢!
public partial class TextViewer : System.Web.UI.Page
{
public HttpContext ctx;
protected void Page_Load(object sender, EventArgs e)
{
HtmlGenericControl myDiv = new HtmlGenericControl("div");
myDiv.Style.Add(HtmlTextWriterStyle.BackgroundColor, "Blue");
this.Controls.Add(myDiv);
ctx = this.Context;
}
protected void Button1_Click(object sender, EventArgs e)
{
ctx.Response.Write("supposed to be printed inside myDiv.");
}
}
答:
0赞
Tarek Abdel Maqsoud
7/18/2016
#1
在这种情况下,您可以将文本拆分为多个跨度,并分别设置每个跨度的文本
foreach(var paragraph in myText)
{
var span = new HtmlGenericControl("span");
span.InnerHtml = paragraph;
myDiv.Controls.Add(span);
}
1赞
Denys Wessels
7/18/2016
#2
您可以写入 from 代码隐藏并从 jQuery 访问其值。HttpContext
代码隐藏:
protected void Page_Load(object sender, EventArgs e)
{
HtmlGenericControl myDiv = new HtmlGenericControl("div");
myDiv.ID = "myDiv";
myDiv.Style.Add(HtmlTextWriterStyle.BackgroundColor, "Blue");
this.Controls.Add(myDiv);
}
protected void Button1_Click(object sender, EventArgs e)
{
HttpContext.Current.Application["MyData"] = "Supposed to be printed inside myDiv.";
}
.ASPX文件:
<head runat="server">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
var data = '<%= HttpContext.Current.Application["MyData"] != null ? HttpContext.Current.Application["MyData"].ToString() : "" %>';
$("#myDiv").append(data);
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</form>
</body>
评论
0赞
Prabesh
7/18/2016
谢谢。这真的很有帮助。有没有办法在不使用 javascript 的情况下做到这一点?
0赞
Prabesh
7/18/2016
现在,我创建了一个方法,而不是每次从文本文件中读取新行时调用的按钮单击。但什么都没有打印。使用调试器运行时,它显示 jQuery 功能仅访问一次。有办法吗?
0赞
Denys Wessels
7/19/2016
你不能这么做。这不是网络的工作方式。在服务器上构造页面并将其发送到客户端。您需要将文本文件的全部内容读入一个变量并设置一次
评论