2014年7月13日 星期日

[RESOLVED] Render a Control into string at WebServices


Hi there,


I am trying to render the content of a control into a string while requesting a webservice.


I was already trying some different ways. Some returned an empty string and one throws an exception. Experimentaly I tried to place the content into a Page and get the Panel to render it but the page said it had no controls at all.


The way(which I was trying very hopefully) with the exception I have mentioned is the following


ImageElement ie = (ImageElement)new Page().LoadControl("~/Controls/ImageElement.ascx");

and it says something like ""Galerie.Controls.ImageElement"
is not allowed here
because the class
"System.Web.UI.UserControl"
is not expanded.
" (original in german is says: "Galerie.Controls.ImageElement" ist hier nicht zulassig, da die Klasse "System.Web.UI.UserControl" nicht erweitert wird.)


Init a new instance by new ImageElement(); always returns an empty string, even if it is a modified render-method or not.


Creating a new Page by new Page(); and insert a new Form with an inserted ImageElement-Object did not the job either.


What have I to do get the render-string? Is it a bit tricky because I am working in a werbservice? Is there maybe  a property to set at the beginning of the webservice-method?



Thank you!!



Create a new class


public class FormlessPage : System.Web.UI.Page
{
public override void VerifyRenderingInServerForm(System.Web.UI.Control control)
{
}
}

Your webservice method


[WebMethod]
public void RenderControl()
{
FormlessPage p = new FormlessPage();
MyUserControl c = (MyUserControl) new System.Web.UI.Page().LoadControl("~/MyUserControl.ascx");
p.Controls.Add(c);
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter w = new System.Web.UI.HtmlTextWriter(sw);
HttpContext.Current.Server.Execute(p, w, false);
string html = sw.ToString();

However from the error message you're getting, I think the issue is that your ImageElement.ascx does not derive from UserControl.  It's definition must be something like


public partial class MyUserControl : System.Web.UI.UserControl




Hey, thanks for the reply. I have tried this kind of solution already, but tried yours again. But no success with it too. It throws the exception on the same place as before. The ImageElement derives already from the UserControl, it has the following declaration:


public partial class ImageElement : System.Web.UI.UserControl

Currently I do not have any idea...




I think i did it.



The problem was the namespace - I need to set the same namespace for the ImageElement as for the UserControl (System.Web.UI).


沒有留言:

張貼留言