Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering ASPX Page without a request

Tags:

c#

asp.net

I have an ASPX page that I intend to use as a template to generate some HTML. I have defined my markup and data bound controls and built a function to do all the data binding, call this.Render and return the HTML. The function works just fine when called from Page_Load.

My intent was to bypass page request and directly call the method and get the page HTML, but when I call the function without making a HTTP Request, none of my server side controls are initialized.

Is there any way I can call a method on a page, pass some params and get the HTML output without making a HTTP Request. I believe Server.Execute could do it but i cant find a way to pass params in it.

I am calling the function like this

MyPage ThreadHTMLGenerator = new MyPage;
string threadHTML= ThreadHTMLGenerator.GenerateExpandedHTML(param1, param2, param3);
like image 708
Midhat Avatar asked Feb 22 '11 15:02

Midhat


1 Answers

You need to use Server.Execute:

var page = new MyPage();
StringWriter writer = new StringWriter();
HttpContext.Current.Server.Execute(page, writer, false);

Alternatively if you need to pass your own querystring parameters, you could do a WebRequest to yourself:

var request = WebRequest.Create("http://www.mysite.com/page.aspx?param1=1&param2=2");
var response = (HttpWebResponse)request.GetResponse ();
var dataStream = response.GetResponseStream ();
var reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
like image 178
Keltex Avatar answered Oct 19 '22 15:10

Keltex