how to get inner html from current aspx page in code behind - asp.net

How would I be able to get the innerHtml of the current aspx page in codebehind? I want to use the innerHTML and pass to a pdf converter function when the user clicks the pdf button, but i need the current page html as string.

I would do a postback and use javascript to provide the current innerHTML
__doPostBack(**event target**, document.documentElement.innerHTML);

You can override Render method of the page.
protected override void Render(HtmlTextWriter writer)
{
StringBuilder sb = new StringBuilder();
HtmlTextWriter tw = new HtmlTextWriter(new StringWriter(sb));
base.Render(tw);
string innerHtml = sb.ToString();
}
innerHtml will contain whole rendered html code of page. A little simplified version.

Related

Exporting GridView To Excel Requires GridView To Be Placed In a Form Tag

Been trying to export the content of the gridview, which is placed in a ContentPlaceHolder, to Excel.
Obviously no form tag is included in the .aspx page. It's in the master page.
This line gvRapor.RenderControl(hwr);
gives the error:
Control 'cphIcerik_gvRapor' of type 'GridView' must be placed inside a form tag with runat=server.
the code:
StringWriter swr = new StringWriter();
HtmlTextWriter hwr = new HtmlTextWriter(swr);
for (int j = 0; j < gvRapor.Rows.Count; j++)
{
GridViewRow row = gvRapor.Rows[j];
gvRapor.RenderControl(hwr);
Context.Response.Write(swr.ToString());
Context.Response.Flush();
Context.Response.End();
}
Tried almost all possible values for Response.ContentType, but the same!
I think you are calling gvRapor.RenderControl(hwr); and i guess you would not have overloaded the VerifyRenderingInServerForm
Try by adding the following code in your file
public override void VerifyRenderingInServerForm(Control control)
{
/* HtmlForm control is rendered at run time. */
}
Have a look at this VerifyRenderingInServerForm
I hope this helps!

How to get autopost back on a control when rendered

I have to add a dropdown control in the web part.
I am rendering the part using HTML Strings as follows...
StringBuilder sb = new StringBuilder();
sb.Append(div id="content); There are quotes in the string
sb.Append(div class=""hb"">");
*sb.Append(div class=""someclass"">");*
sb.Append(h2 id=""contentpage_title"">Title");
**sb.Append(div class=""ctn_conferences"">");**
writer.Write(sb.ToString());*
I have to add a loaded dropdown control...so I declared..
protected DropDownList ddMyDropDown = new DropDownList();
Then added the control in the middle of the render where I wanted as follows...
ddMyDropDown.RenderControl(writer);
Everything is fine....except... the post back does not work.
My event handlers are not getting executed.
When I add the control ...like Controls.Add(Control) then it adds at the bottom of the part. That is not what I want.
So how do I get the post back to work?
Thanks in advance.
-Satyen
You've got the right idea for the render method override but add the following:
protected DropDownList ddMyDropDown;
protected override void CreateChildControls()
{
base.CreateChildControls();
ddMyDropDown = new DropDownList();
ddMyDropDown.AutoPostBack = true;
Controls.Add(ddMyDropDown);
}
Also, in the render method override call EnsureChildControls() before you try and render any control setup through the CreateChildControls() method.

Use ASP.Net server control code generation from .ashx

I'm trying to take an existing bunch of code that was previously on a full .aspx page, and do the same stuff in a .ashx handler.
The code created an HtmlTable object, added rows and cells to those rows, then added that html table the .aspx's controls collection, then added it to a div that was already on the page.
I am trying to keep the code in tact but instead of putting the control into a div, actually generate the html and I'll return that in a big chunk of text that can be called via AJAX client-side.
HtmlTable errors out when I try to use the InnerHtml property (says it isn't supported), and when I try RenderControl, after making first a TextWriter and next an HtmlTextWriter object, I get the error that Page cannot be null.
Has anyone done this before? Any suggestions?
*Most recent is above.
OK, even after Matt's update there is a workaround ;)
Firstly, we have to use a page with form inside. Otherwise we won't be able to add a ScriptManager control. One more thing: the ScriptManager control should be the first control in the form. Further is easier:
Page page = new Page();
Button button = new System.Web.UI.WebControls.Button
{
ID = "btnSumbit",
Text = "TextButton",
UseSubmitBehavior = true
};
HtmlForm form = new HtmlForm
{
ID="theForm"
};
ScriptManager scriptManager = new ScriptManager
{
ID = "ajaxScriptManager"
};
form.Controls.Add(scriptManager);
form.Controls.Add(button);
page.Controls.Add(form);
using (StringWriter output = new StringWriter())
{
HttpContext.Current.Server.Execute(page, output, false);
context.Response.ContentType = "text/plain";
context.Response.Write(output.ToString());
}
This works. The output is quite large so I decided not to include it into my answer :)
Actually, there is a workaround. Yep, we may render a control in handler.
Firstly, we need a formless page. Because without it we get:
Control 'btnSumbit' of type 'Button'
must be placed inside a form tag with
runat=server.
public class FormlessPage : Page
{
public override void VerifyRenderingInServerForm(Control control)
{
}
}
Secondly, nobody can prevent us from creating an instance of our FormlessPage page. And now let's add a control there (I decided to add a Button control as an example, but you could use any).
FormlessPage page = new FormlessPage();
Button button = new System.Web.UI.WebControls.Button
{
ID = "btnSumbit",
Text = "TextButton",
UseSubmitBehavior = true
};
page.Controls.Add(button);
Thirdly, let's capture the output. For this we use HttpServerUtility.Execute method:
Executes the handler for the specified
virtual path in the context of the
current request. A
System.IO.TextWriter captures output
from the executed handler and a
Boolean parameter specifies whether to
clear the
System.Web.HttpRequest.QueryString and
System.Web.HttpRequest.Form
collections.
Here is the code:
using (StringWriter output = new StringWriter())
{
HttpContext.Current.Server.Execute(page, output, false);
context.Response.ContentType = "text/plain";
context.Response.Write(output.ToString());
}
The result will be:
<input type="submit" name="btnSumbit" value="TextButton" id="btnSumbit" />
In addition I can recommend ScottGu's article Tip/Trick: Cool UI Templating Technique to use with ASP.NET AJAX for non-UpdatePanel scenarios. Hope, you could find a lot of useful there.
Another option is to host the ASP.NET HTTP pipeline in your process, render the page to a stream and read the HTML you need to send from the HttpListenerContext.Response.OutputStream stream after the page has been processed.
This article has details: http://msdn.microsoft.com/en-us/magazine/cc163879.aspx

How get html of current page?

I want parse the html of current page.
How can I get the html of current page for that in asp.net?
Thanks in advance.
for client side
In Internet explorer
Right click on the browser --> View source
IN firefox
Right click on the browser --> View Page Source
for server side
You can override the page's render method to capture the HTML source on the server-side.
protected override void Render(HtmlTextWriter writer)
{
// setup a TextWriter to capture the markup
TextWriter tw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(tw);
// render the markup into our surrogate TextWriter
base.Render(htw);
// get the captured markup as a string
string pageSource = tw.ToString();
// render the markup into the output stream verbatim
writer.Write(pageSource);
// remove the viewstate field from the captured markup
string viewStateRemoved = Regex.Replace(pageSource,
"<input type=\"hidden\" name=\"__VIEWSTATE\" id=\"__VIEWSTATE\" value=\".*?\" />",
"", RegexOptions.IgnoreCase);
// the page source, without the viewstate field, is in viewStateRemoved
// do what you like with it
}
Override Render method and call base.Render with you own HtmlWriter.
Do you really want to parse HTML? It's a tricky business. If you don't absolutely have to do it, I'd avoid it by using DOM methods client-side (if a client-side solution is acceptable). If you're doing a lot of it, you might consider jQuery, Prototype, or some other tool to help.

get HTML of current page without ViewState ASP.Net

Is there any way through which I can get HTML of my current page. By current page I mean let's say I am working on Default.aspx and want to get HTML by providing a button on it.
How to get it.
EDITED in response to clarification of the requirements
You can override the page's render method to capture the HTML source on the server-side.
protected override void Render(HtmlTextWriter writer)
{
// setup a TextWriter to capture the markup
TextWriter tw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(tw);
// render the markup into our surrogate TextWriter
base.Render(htw);
// get the captured markup as a string
string pageSource = tw.ToString();
// render the markup into the output stream verbatim
writer.Write(pageSource);
// remove the viewstate field from the captured markup
string viewStateRemoved = Regex.Replace(pageSource,
"<input type=\"hidden\" name=\"__VIEWSTATE\" id=\"__VIEWSTATE\" value=\".*?\" />",
"", RegexOptions.IgnoreCase);
// the page source, without the viewstate field, is in viewStateRemoved
// do what you like with it
}
Not sure why you want what you want, but... this is off the top of my head, i.e. I didn't try this code.
Add a client-side onclick to your button to show markup and do something like this:
function showMarkup() {
var markup = "<html>" + document.getElementsByTagName("html")[0].innerHTML + "</html>";
alert(markup); // You might want to show a div or some other element instead with the markup variable as the inner text because the alert might get cut off.
}
If you need this rendered markup posted back to the server for some reason, store the encoded markup in a hidden input and post that back. You can register the script below on the server-side using ClientScriptManager.RegisterOnSubmitStatement . Here's the cleint-side code.
var markup = escape("<html>" + document.getElementsByTagName("html")[0].innerHTML + "</html>");
var hiddenInput = $get('hiddenInputClientId');
if (hiddenInput) {
hiddenInput.value = markup;
}
Hope that helps,
Nick
I'm still not sure what your objective is with this. But if you want the total rendered output of the page then your probably better of looking at some client side code as this would be run once the server has returned the fully rendered HTML.
Otherwise you could proably catch the page unload event and do something with the rendered content there.
More info needed on what you want from this.

Resources