How to include text inside div using HttpContext?

884 Views Asked by At

I have included a div in my web page using HtmlGenericControl. With a button click , i want to add text inside the div using HttpContext. I don't want to use InnerHtml because the browser hangs when the text i want to include is very long. I tried the following way but it prints the text outside the div. Please Help. Thanks!

 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.");
    }
}
2

There are 2 best solutions below

3
Denys Wessels On BEST ANSWER

You can write to the HttpContext from code behind and access its value from jQuery.

Code behind:

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
Tarek Abdel Maqsoud On

In such case, you can split your text into many spans and set each span's text separately

foreach(var paragraph in myText)
 {
    var span = new HtmlGenericControl("span");
    span.InnerHtml = paragraph; 
    myDiv.Controls.Add(span);
 }