2010-06-08 9 views
1

Je veux renvoyer la sortie HTML du contrôle à partir d'un gestionnaire. Mon code ressemble à ceci:C# asp.net Comment retourner un usercontrol à partir d'un handler ashx?

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; 
    } 
} 

}

Je reçois l'erreur:

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();

Comment puis-je retourner la sortie d'un Usercontrol via un gestionnaire?

Répondre

2

Utilisez la méthode BuildManager.GetCompiledType pour charger une page existante avec le contenu souhaité, définissez certaines propriétés publiques à l'aide de l'implémentation de l'interface et appelez sa requête process castée dans httphander. De cette façon, vous n'exposez pas les pages aspx directement et vous pouvez dessiner différentes pages pour différents paramètres à partir de la même ressource ashx. Il est également important de conserver les avantages et la puissance des pages asp.net.

1

Vous pouvez essayer ceci:

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);