Legion
Legion

Reputation: 791

Open a static Html string (builded up at runtime) from code behind

there is a smooth way to open a static html string from code behind whitout writing it to a file? At the moment i'm doing something like below:

 using (StreamWriter sw = new StreamWriter("\\mypath\\test.html",false))
 {
      sw.Write(my_html_string); //I build 'my_html_string' inside the code
 }
 Response.Redirect("http://mysite/mypath/test.html");

but what i'd like to do is something like:

Page.Show(my_html_string);

without wasting time writing it to a file.

Thanks,

Upvotes: 0

Views: 123

Answers (1)

pfx
pfx

Reputation: 23224

The most raw way for doing this is via an IHttpHandler.

In Visual Studio via menu: Add > New Item ... > Generic Handler.
You end up with an .ashx and a corresponding .ashx.cscodebehind file where you write your code.

You navigate to http://yourwebite/<nameOfYourHttpHandler>.ashx to see the rendered html.
An HttpHandler can be part of routing and can also accept querystring parameters.

MyHandler.ashx

<%@ WebHandler Language="C#" CodeBehind="MyHandler.ashx.cs" Class="PFX.MyHandler" %>

MyHandler.ashx.cs

using System;
using System.Web;

namespace PFX
{
    public class MyHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            // Implement logic to build your html string here.
            String html = "<html><head></head><body><b>foobar</b></body></html>";

            // Set any appropriate http-headers here.
            context.Response.ContentType = "text/html";            
            context.Response.Write(html);
        }

        public Boolean IsReusable
        {
            get { return false; }
        }
    }
}

== EDIT BY LEGION ==

The above code works perfectly, but if you need to pass some value from previous ASPX page to the handler (like me) you need to do like below:

previousPage.aspx.cs

protected void MyButton_Click(object sender, EventArgs e)
{
     String my_html_string = string.empty;
     //Code that build the html String
     HttpContext.Current.Application["my_key_name"] = my_html_string;
     Response.Redirect("~/myHandler.ashx");
}

MyHandler.ashx.cs

public class MyHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";
            context.Response.Write(context.Application["my_key_name"]);
        }

        public Boolean IsReusable
        {
            get { return false; }
        }
    }

Upvotes: 1

Related Questions