I've seen it time and time again the typical answer being something like this:
public string RenderControlToHtml(Control ControlToRender)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.IO.StringWriter stWriter = new System.IO.StringWriter(sb);
System.Web.UI.HtmlTextWriter htmlWriter = new System.Web.UI.HtmlTextWriter(stWriter);
ControlToRender.RenderControl(htmlWriter);
return sb.ToString();
}
... This is fine if you have simple html tags but when I have a textbox or some other asp control in my control it throws a wobbly about the control not being on a form (which in fact it is because im trying to render a portion of the page to a string that i can then send as an email)
So ...
I'm pretty sure this has been asked and answered before but i'm at a loss for finding a real answer that actually works ...
How do i render the html output of both server and client side controls to a html string in .Net 4.0 because seemingly the above is not good enough?
Note:
I have found examples that tal开发者_运维技巧k about doing this at page level ...
public override void VerifyRenderingInServerForm(Control control)
{
//Do nothing (we dont care if theres a form or not)
}
... and disabling event validation but apparently that's not working for me either.
Is there a way to do this without a "hack" thats clean?
Also:
I even tried creating a new page, adding a form to it, added my control to that then calling renderControl on that page to which i got more errors.
EDIT: I've been digging around and I think the problem might be related to postbacks or something because i found this: http://forums.asp.net/t/1325559.aspx
Another thing that might be putting a bit of a spanner in the works is my use of the ajax toolkit, I essentially need only the visible portion of the control which seems to give a bit of a headache for updatepanels for some reason.
I'm guessing the above sample works only on basic .net controls that are not ajax toolkit related.
What further complicates the issue is that I would like to get the control in its current state when a button is clicked at the bottom of it ...
Essentially the control represents a form for booking an MOT and I would like to render the form filled in to an email that is then sent to the garage if that makes sense.
I'm thinking i may have to admit defeat here and simply get the markup from the client and manually build an email pulling out the control values as this seems to be a compatability issue between ajax controls and the renderControl method from what i can tell (maybe you cant render a partial postback compatible control in this fashion).
Unless someone smarter than me can prove it can be done ???
Create an ajax control extender and get the html markup on the client side then post that back to the server for processing, it's a bit of hack but it seems that anything involving ajax controls will cause the default recommended mechanism to break.
精彩评论