Show the server-side generated HTML in a new window - c#

What is the best way to show the server-side generated HTML (full page) into a new popup window? It should be triggered upon clicking a button (causing a postback to the server).
Thanks
Edited:
The HTML content are dynamically generated in the code behind and the content is full page (<html> ... </html>). Upon clicking a button on the web page, I would like to get the generated html content and pass it to the browser and show it in a new popup window. The content will be the final result (UI) not HTML tags.

You can send the same page with mime type text/plain
For instance with a
<a href="same url?mime=textonly" target="_blank">
On the asp server, when the argument mime=textonly is detected, you change the mime type to text/plain

Perhaps I should have started with a comment to get more information but can you not:
Post back to a new window on click? <a target="_blank">
Though if the requirement is for the server to generate the new window, just append something like:
<script>window.open('title'); </script> at the end of the response and have the server populate that.

You could probably have the server code save the HTML to a file and output <script>window.open('urltothefile');</script>. Just make sure that you write a unique filename each time.
Alternatively, you could have the server code store all related information into a database and output <script>window.open('showResult.aspx?id=123');</script>, where 123 is the id of the database record. Then in showResult.aspx, have it generate the required HTML.
Another option is to output the HTML into a div with style="display: none", then have some javascript to assign the innerHTML to the newly opened window. eg:
var w = window.open ('_blank');
w.document.body.innerHTML = document.getElementById("returnedHTML").innerHTML
One more possibility is to have a WebMethod. I don't really remember how to declare one, but it is a server function that can be called from the client. Open the window via javascript, call the webmethod and place the result as the innerHTML of the newly opened window; Pretty much like the previous option.
All these are good but they don't work when you use UpdatePanel and partial rendering. If that's the case, it's a whole different story.

Related

Anglesharp HTML parser doesn't seem to be parsing document deep enough to access desired element

So I'm trying to scrape a website using AngleSharp and want to access a particular button that is nested deep in the site. I have logged out the parsed document html with document.DocumentElement.OuterHtml
but can only see so far into the document:
<div class="l-propertySearch-paginationAndSearchFooter" data-test="pagination">
<div data-bind="component: 'pagination'"></div>
</div>
</div>
However, when I inspect the page in the web browser, I can see the additional layers necessary to access the button:
As you can see, the div with the data-bind attribute title "component: 'pagination'" open up further but doesn't display this in the log - this is why, I suspect, I can't retrieve the element.
I've experimented with document.QuerySelectorAll("button" and get back a list of buttons but not the one I'm after - it's like the particular block I want doesn't exist. Any ideas what I'm doing wrong?
As far as I understand that button you are looking for is created with javascript and does not exist in original source code. That is the reason you can't access that button with anglesharp. Right click on website and click View page source (Ctrl + U on chrome) and look for your button there. That is what anglesharp sees not html inside inspect element.

Include HTML webform in ASP/C# on page load

I made a webform in html and I have a website in C#.
I would like this form to show up every time the page is loaded.
What is the best way to integrate/include/call the form?
Which pages I have to modify? Default.Aspx or Default.Aspx.cs?
The purpose of this project is to show this form everytime the cookies is not set in the aspx code.
Which I guess I have to modify the aspx part that checks if the value of the cookie is set or not and show/not show the webform based on this value.
You could do this using a combination of JavaScript (to check if cookies are enabled) and JQuery. If cookies aren't enabled, have a placeholder DIV that can hold the HTML content you wanted to show. Then use $.ajax (http://api.jquery.com/jquery.ajax/) to load the html content from browser and set the DIV's innerHTML property with the returned HTML.
Hope this works for you!!
Some little progress.
That's how I modified my pages for my needs. In this way the html webform is diplaying correctly.
In the head of default.master I added:
in the default.aspx I added:
with the entire html of my html page (tag html included).
Now I need to modify this page that in the way this pop up is showed only if a cookie value is not set.

C# Setting InnerHtml to "" for an element which is updated by server causes element to stop updating

I have a C# Windows Forms Application with a webBrowser within it. It visits a Wikia chatroom, where it then locates the element which contains the chat output. This element looks like:
<div style="" id="Chat_XXXXX" class="Chat">
<ul>
(chat text)
</ul>
</div>
The purpose of the program is to retrieve the chat text every once in a while for logging purposes. This is easily done by parsing the "InnerHtml" of the "Chat_XXXXX" element. However, I also need to clear the text from the window when I do this (for various reasons, I cannot leave the text in the window). I figured I would just erase the chat text portion of the element, as this is how it is done with a handy javascript file called "chat hacks" for Wiki chat (here). Or at least, I think that's how it does it. If you look at the function "clearWindow" in that file, you can see what it does:
NodeChatController.prototype.clearWindow = function() {
this.viewDiscussion.chatUL.html('');
this.inlineAlert(i18n['cleared']);
}
I have tried setting the InnerHtml of "Chat_XXXXX" using the following three strings (not all at the same time, of course):
HtmlDocument document = webBrowser1.Document;
document.GetElementById("Chat_XXXXX").InnerHtml = ""
document.GetElementById("Chat_XXXXX").InnerHtml = "<ul></ul>"
document.GetElementById("Chat_XXXXX").InnerHtml = "<ul><li class=\"inline-alert\"> Window cleared. </li></ul>"
However, although these clear the window (and in the case of the last one prints a message), the chat no longer updates as new messages show up. The only fix is to reload the page, which isn't an option, because reloading the page brings in a whole load of chat history (which I'm trying to avoid). I've also tried importing that javascript mentioned above into the page using:
HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");
scriptEl.SetAttribute("type", "text/javascript");
scriptEl.SetAttribute("src", "https://db.tt/66q8UQbY");
head.AppendChild(scriptEl);
This javascript creates a button which clears the chat window. The button clears the window just fine, but again, the chat no longer updates. I know this button works correctly without stopping further incoming chat in "regular" browsers (Chrome, Firefox, Opera, etc). I've used it many times, and the script itself is quite popular in the Wikia community. I've already followed the steps here: "WPF WebBrowser Control - position:fixed Element jumps while scrolling (Windows 8)" to get the browser to act as close as it can (?) to Internet Explorer. I've already checked the Body field of the document after altering the InnerHtml to make sure that my replacements didn't alter anything important. Just for clarity, here's an example of what is contained in the (chat text) portion of my original example:
<li class="you" data-user="UserNameHere" id="entry-c812">
...avatars and junk...
<span class="message">hello</span>
</li>
I honestly have no idea what could be causing the chat element to stop updating after it has been edited (especially since it works outside of this program), so I don't know what information to include. Whatever you need, I'll provide it. Here's the javascript from Wikia which generates the chat output window: chat_js2. Look for "Chat_" to find the part which originally generates the window. I don't know where the output is updated in that file though.

Invalid ViewState when using jQuery tabs

I have a fairly simple page with a set of jQuery tabs, the content of some is called via ajax. I also have a search box in the masterpage in my header.
When I open the tabbed page the search box works fine. However once I have clicked on one of the ajax tabs the search box fails to work with an "Invalid Viewstate" yellow screen of death.
I believe this is because the ajax page is replacing the __VIEWSTATE hidden input with its own.
How can I stop this behaviour?
UPDATE: I have noticed that the YSOD only appears in IE and Chrome, Firefox doesn't seem to have the same issue. Although how the browser influences the ViewState, I'm not sure.
UPDATE: I've put a cut down version of the site that shows the issue here: http://dropbox.com/s/7wqgjqqdorgp958/stackoverflow.zip
The reason of such behavior is that you getting content of the ajaxTab.aspx page asynchronously and paste it into another aspx page. So you getting two instances of hidden fields with __VIEWSTATE name and when page posted back to server theirs values are mixing (might depends on how browser process multiple controls with same name on submit). To resolve this you can put second tab's content into a frame:
<div id="tabs">
<ul>
<li>Default Tab</li>
<li>ajax Content</li>
</ul>
<div id="tabs-1">
<p>
To replicate the error:
<ul>
<li>First use the search box top right to search to prove that code is ok</li>
<li>Then click the second ajax tab, and search again.</li>
<li>N.B. Chrome / IE give a state error, Firefox does not</li>
</ul>
</p>
</div>
<iframe id="tabs-2" src="ajaxTab.aspx" style="width:100%;" ></iframe>
</div>
Also, I'm not sure but this seems like error in the Web_UserControls_search control. In my opinion, NavBarSearchItemNoSearchItem_OnClick method must be refactored as below:
protected void NavBarSearchItemNoSearchItem_OnClick(object sender, EventArgs e)
{
var searchFieldTbx = NavBarSearchItemNo;
var navBarSearchCatHiddenField = NavBarSearchCatHiddenField;
var term = searchFieldTbx != null ? searchFieldTbx.Text : "";
if (term.Length > 0) //There is actually something in the input box we can work with
{
//Response.Redirect(Url.GetUrl("SearchResults", term));
Response.Redirect(ResolveClientUrl("~/Web/SearchResults.aspx?term=" + term + "&cat=" + navBarSearchCatHiddenField.Value));
}
}
Draw attention that we resolving client url when redirecting to search results page and instead of navBarSearchCatHiddenField use navBarSearchCatHiddenField.Value as cat parameter.
I guess that you use AJAX to fill the content of the tab. So in this case, content of your tab will be replaced by the new one from ajax and certainly _VIEWSTATE will be replaced. At server, do you use data from ViewState? In the "static tabs", you should prevent them auto reload by using cache:true
Your issue is that with your ajax call you bring in a complete ASPX page. Including the Form tag and its Viewstate. If you remove the Form tag from ajaxTab.aspx you will see everything works fine. asp.net does not know how to handle two Form tags in one page. Same goes for hidden Viewstate fields. You cannot bring in a full aspx page via ajax. Just bring in the content Div you want to display and you`ll be good to go.

Difference between Response.Write() and ClientScript.RegisterStartupScript()?

What is the difference between Response.Write() and ClientScript.RegisterStartupScript()
Thank you.
The Response.Write method can be used to output code during the rendering phase of the page. The <%= %> server tag is a shortcut for <%Response.Write( )%>.
If you use Response.Write from the code behind, you will write to the page before it has started rendering, so the code will end up outside the html document. Eventhough the browser will execute the code, it doesn't work properly. Having something before the doctype tag will make the browser ignore the doctype and render the page in quirks mode, which usually breaks the layout. Also, as the script runs before anything of the page exists, the code can't access any elements in the page.
The ClientScript.RegisterStartupScript method is the preferred way of adding script dynamically to the page. It will render the script at the end of the form so that it doesn't break the html documnet, and it can access the elements in the form.
Also, you give each script an identity, which means that duplicates are removed. If a user control registers a script, and you use several instances of the user control, the script will only be rendered once in the page.
There is a huge difference.
Basically Response.Write will write to your response stream right now, normally this will put whatever you write at the very top of your page output, even before the tag (unless you call it after the page render event).
When you use RegisterStartupScript it will wait and write your JavaScript to the response stream after the page's controls have rendered (IE, the controls wrote their HTML to the response stream). This means the JavaScript you register will be executed by the browser after the other HTML before it has been loaded into the DOM. This is very similar to the event. Another thing this does is if “registers” the script so if you have more than one control on the page that both need that JavaScript they can check to see if it’s already been registered so it’s only rendered once and both controls use it client side.
Hopefully that makes sense, there are more details then that but I tried to keep it simple.
Response.Write
The Write method writes a specified
string to the current HTTP output.
ClientScriptManager.RegisterStartupScript
Registers the startup script with the
Page object.
As I think, both these methods are unrelated. Response.Write() can be used to write something on page that is rendered. While ClientScript.RegisterStartupScript() can be used for registering a javascript on page start up.

Categories

Resources