1

我想从处理程序返回控件的 HTML 输出。我的代码如下所示:

使用系统;使用 System.IO;使用 System.Web;使用 System.Web.UI;使用 System.Web.UI.WebControls;

公共类 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;
    }
}

}

我收到错误:

“/CMS”应用程序中的服务器错误。你调用的对象是空的。说明:执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

异常详细信息:System.NullReferenceException:对象引用未设置为对象的实例。

源错误:

第 14 行:System.Web.UI.Page 页面 = new System.Web.UI.Page(); 第 15 行:UserControl ctrl = (UserControl)page.LoadControl("~/Controls/CalendarMonthView.ascx"); 第 16 行:page.Form.Controls.Add(ctrl); 第 17 行:
第 18 行:StringWriter stringWriter = new StringWriter();

如何通过处理程序返回用户控件的输出?

4

3 回答 3

2

使用 BuildManager.GetCompiledType 方法加载具有所需内容的现有页面,使用接口实现设置一些公共属性并将其 processrequest 调用转换为 httphander。通过这种方式,您不会直接公开 aspx 页面,并且可以为来自同一 ashx 资源的各种参数指定不同的页面。保持 asp.net 页面的优点和功能也很重要。

于 2012-04-18T11:37:21.763 回答
1

你可以试试这个:

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);
于 2014-02-11T06:28:07.947 回答
0

您不能只new创建一个这样的页面类的实例并让它正常工作。我相当确定您需要通过调用GetCompiledPageInstance来创建它(基于此处的讨论)。

于 2010-06-09T00:04:22.450 回答