c# asp.net How to return a usercontrol from a handeler ashx?
I want to return the HTML output of the control from a handler. My code looks like this:
using System; using Syste开发者_如何学JAVAm.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?
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.
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);
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).
精彩评论