Reputation: 21522
I want to return the HTML output of the control from a handler. My code looks like this:
using System; using System.IO; using System.Web; using System.Web.UI; using System.Web.UI.WebControls;
public class PopupCalendar : IHttpHandler {
public void ProcessRequest (HttpContext context) { context.Response.ContentType = "text/plain"; System.Web.UI.Page page = new System.Web.UI.Page(); UserControl ctrl = (UserControl)page.LoadControl("~/Controls/CalendarMonthView.ascx"); page.Form.Controls.Add(ctrl); StringWriter stringWriter = new StringWriter(); HtmlTextWriter tw = new HtmlTextWriter(stringWriter); ctrl.RenderControl(tw); context.Response.Write(stringWriter.ToString()); } public bool IsReusable { get { return false; } }
}
I'm getting the error:
Server Error in '/CMS' Application. Object reference not set to an instance of an object. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 14: System.Web.UI.Page page = new System.Web.UI.Page(); Line 15: UserControl ctrl = (UserControl)page.LoadControl("~/Controls/CalendarMonthView.ascx"); Line 16: page.Form.Controls.Add(ctrl); Line 17:
Line 18: StringWriter stringWriter = new StringWriter();
How can I return the output of a Usercontrol via a handler?
Upvotes: 1
Views: 2598
Reputation: 21
You can try this:
System.Web.UI.Page page = new System.Web.UI.Page();
UserControl ctrl = (UserControl)page.LoadControl("~/Controls/CalendarMonthView.ascx");
page.Form.Controls.Add(ctrl);
ctrl.DoSomething();
context.Response.CacheControl = "No-Cache";
context.Server.Execute(page, context.Response.Output, true);
Upvotes: 1
Reputation: 21
Use BuildManager.GetCompiledType method to load an existing page with desired content, set some public properties using interface implementation and call its processrequest casted into httphander. In this way you do not expose the aspx pages directly and you can deside different pages for various parameters from the same ashx resource. It is also important that you keep the benefits and power of asp.net pages.
Upvotes: 2
Reputation: 20256
You can't just new
up an instance of a page class like that and have it properly work. I'm fairly certain you need to create it with a call to GetCompiledPageInstance (based on discussion here).
Upvotes: 0