Internet Explorer 8 now running code showing in view source - c#

So I have a server control that is at the bottom of my page:
<%= addPopup() %>
Here is the code for it:
protected String addPopup()
{
if (usedSearch == false)
{
return "";
}
else
{
return "<body id=\"test\" onload=\"popup.show()\" runat=\"server\">";
}
}
Basically, depending on what the user does, usedSearch will be true or false, resulting in the HTML line being added to the page:
<body onload="popup.show()" runat="server">
What this does is show a popup to the user, I do this so that it shows on postback when needed.
This works in all major modern browsers. It does not work in Internet Explorer 8 even though it is showing up in the code behind for every browser including IE8. How do I get IE8 to show the popup when is part of the page source?

You are rendering duplicated body tag, probably that's the reason why IE does not pick it up. You should rather output javascript snippet at the bottom of your page, before </body> tag:
<script type="text/javascript">
if (window.addEventListener) {
window.addEventListener('load', popup.show, false);
}
else if (window.attachEvent) {
window.attachEvent('onload', popup.show );
}
</script>
It would attach your function to onLoad event in all browsers.
P.S. Just make sure that your popup.show function is initialized before this code.

Related

Razor server side code block and Jquery

My application is MVC5 c#, trying to execute the following:
#{
var s = Model.PhysicalExam;
if (s == null)
{
<script>
alert("1");
$("#newSale1").hide();
</script>
}
else
{
<script>
alert("2");
$("#newSale1").show();
</script>
}
}
Alert works, however does not hide or show the button. Would appreciate your suggestions.
I would guess that newSale1 maybe isn't loaded in the DOM when that script code is executed. You should probably put those blocks inside a document ready event.
$( document ).ready(function() {
console.log( "ready!" );
});
I might go with something like this at the bottom of the page
<script type='text/javascript">
var isExamNull = #((Model.PhysicalExam == null).ToString());
$(document).ready( function(){
if (isExamNull)
$("#newSale1").hide();
else
$("#newSale1").show();
};)
</script>
Putting scripts at the bottom of the page lets the html render first, $(document).ready ensure that, well, the document is ready. Using the #() will write your server side values into your scripts, another technique is to use a hidden and have the script check the value of the hidden.

Execute javascript code at the end of event handler

I'm building a web application on ASP.NET with C#.
On a button click I show a loading image, while the database query is being executed. Then I dynamically create an Excel file and send it to the client like this:
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".xlsx");
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Unicode;
HttpContext.Current.Response.BinaryWrite(p.GetAsByteArray());
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
I get the dialog box, and the loading image stays there.
I've tried placing call to a javascript function (with ClientScript.RegisterStartupScript function) before the code above, it didn't work. As I understand all javascript code is run after all the code-behind has executed, but in this case it doesn't execute at all once the file is sent to the client.
I've also tried creating a separate thread, and removing the loading image there. I put the breakpoint to trace it, code in the thread does execute, but the image still stays there.
Does anyone have an idea how this can be handled? Thank you!
You can only send or transmit 1 mime type in one request/response cycle. (My knowledge in this area is debatable).
That said, you can design a hack around this. Use an iframe on the client to "download the file". You can point its src to an ashx file that does the same.
You need to wire the iframe's onload event, so your web page has someway of knowing that download is done; thats where you can execute your logic.
Solution Update:
Well, after digging around, I've discovered my answer is half-baked!
The issue is that iframes don't trigger their onload event after they download something. The onload event will trigger iff there the url pointed to by src actually navigates to a different page. This is by design I suppose. And I learn that today!
So what then is the work-around?!
Fortunately, you can transmit cookies to the client. On the client your web page has to keep polling for the presence of this cookie. So once your web page is able to detect the presence of the cookie, it means that the browser has completed with the download request. This has been discussed in great detail in the following post:
http://geekswithblogs.net/GruffCode/archive/2010/10/28/detecting-the-file-download-dialog-in-the-browser.aspx
I'll just show you some code relating to the handler file (which simulates a download), and the client (which has an iframe doing the job). This should pretty much give you the gist:
Webform1.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApp.FileDownload.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>iFrame Download</title>
<script type="text/javascript" src="Scripts/jquery-2.1.0.min.js"></script>
<script type="text/javascript" src="Scripts/jquery.cookie.js"></script>
<script type="text/javascript">
function foo() {
console.log('foo');
//execute post-download logic here
}
$(function () {
$('input').click(function () {
//make sure we get rid of the
//cookie before download
$.removeCookie('downloaded');
var intrvl = setTimeout(function () { //this function polls for the cookie through which we track that the file has indeed been downloaded
console.log('timer');
var value = $.cookie('downloaded');
if (value == 'true') {
clearTimeout(intrvl);
foo();
}
}, 1000);
//this initiates the download
$('iframe').attr({
'src': 'download.ashx?id=' + $('#tbxRandomNumber').val()
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="tbxRandomNumber" runat="server"></asp:TextBox>
<input type="button" value="Download" />
<iframe src="about:blank" style="display:none"></iframe>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Next Random Number" />
</div>
</form>
</body>
</html>
I've made used of jquery cookies plugin to help me with handling cookies.
download.ashx:
using System;
using System.Web;
namespace WebApp.FileDownload
{
/// <summary>
/// Summary description for download
/// </summary>
public class download : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.SetCookie(new HttpCookie("downloaded","true")); //setting cookie in the response
string id = context.Request.QueryString["id"] == null ? "NULL" : context.Request.QueryString["id"];
string str = string.Format("Content with id {0} was generated at {1}", id, DateTime.Now.ToLongTimeString());
context.Response.AddHeader("Content-Disposition", "attachment; filename=test.txt");
context.Response.AddHeader("Content-Length", str.Length.ToString());
context.Response.Write(str);
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
It looks like you have a couple of misunderstandings here. You only have one request, and one response from the server. Making new threads is something that only happens on the server, and won't create additional responses.
When you're sending the Excel file, you're using:
HttpContext.Current.Response.Clear();
By clearing the response, you're losing the JavaScript that you added previously. It will never get to the client.
If the processing is fairly trivial (always just a couple of seconds), I'd just set the loading animation to run for a couple of seconds and stop, by setting a timeout on the initial onclick event. It's not perfect, but it'll give the user some immediate feedback.
If the processing is going to take a long or very variable amount of time, then the animation is more important to get right. You can try loading your Excel file in a hidden <iframe>, and attaching an onload event to remove the loading animation.
You would need to create a separate page to handle generating the Excel file, rather than doing it in a server-side OnClick handler. However, I seem to remember that support for onload events on <iframe> can be spotty with older IE versions.
javascript run in the client when page is loading in the browser. You may have a hidden textbox, at the end of you event yo can put a value into that textbox:
txtHidden.Text = "Hola Mundo"
You have to check the value on page load:
<script type="text/javascript">
$(document).ready(function(){
if($("#txtHidden").length > 0 && $("#txtHidden").val() != '')
{
alert($("#txtHidden").val());
}
});
</script>
You can put this in a web user control.
Another solution:
<div class='button' id='btnGenerateDownload' onClick='GenerateDownload(this)'>
Click here <div id='loadingImage' class='loadingImage'></div>
</div>
JQuery:
function GenerateDownload(caller)
{
//add loading gif:
var $loagingGIF = $(caller).children('#loadingImage').eq(0);
$loagingGIF.addClass('loadingImage');
var fileGeneratorUrl = 'ghFileGenerator.ashx';
var downloadHandlerUrl = 'ghDownloadHandler.ashx';
$.post({data: "File1"}, function(response){
//remove gif
$loagingGIF.removeClass('loadingImage');
if(response != '') //file key
{
downloadHandlerUrl += '?key=' + response;
var $link = $("<a />").attr('href', downloadHandlerUrl).html('download');
$link.appendTo($(caller));
}
});
}
css:
.loadingImage{background: transparent url(images/loading.gif);}
.ashx:
string filekey = context.Current.Request.Form("key");

jquery tab asp.net staying on tab after postback 0x800a01b6

Hello i need to stay on a jquery tab after asp.net postback, but nothing what i found here or somewhere else in the web works for me.
I tried:
Staying on current jQuery tab across post back?
and
Jquery postback, maintain same tab after postback
but also some other sources.
Everytime when im changing
$("#tabs").tabs();
to something like:
$(function () {
$("#tabs").tabs({
show: function() {
var selectedTab = $('#tabs').tabs('option', 'selected');
$("#<%= hdnSelectedTab.ClientID %>").val(selectedTab);
},
selected: <%= hdnSelectedTab.Value %>
});
});
With hiddenfield etc. i get this error 0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'tabs'.
When im Using the jquery.cookie.js file with this code:
$("#tabs").tabs({ cookie: { expires: 1 } });
i dont get an error but i dont stay on the tab after postback.
You can give your input button a css class.
#inputField {
display:none !important;
}
Save this as yourCssClass.css
document.getElementById("inputField ").className += "yourCssClass";
Add this to your JavaScript
I found out what the Problem was, I inserted jquery on the end of my master page because of that somehow it overwrote the jqueryui file in that specific aspx file. After i added the jqueryui.js file after the jquery.js everything worked fine.

Variable from javascript function in aspx page accessible in c# code in same javascript function

My code in aspx page is:
<script type="text/javascript">
function MenuItem_Click(itemId) {
<%
MyAspLogger("Clicked on item: {0}", itemId);
%>
}
</script>
I don't know how to access "itemId". I know that from other side - accessing c# variable in aspx code it is possible. But I don't know if is possible access javascript variable in c# code include in same javascript function.
Thank you for your help.
I guess you are tryingto get the clicked menu ids, and then log all clicked menu item?
1- To get the menu id,
Pass the menu object using keyword "this" to the function handling the click (MenuItem_Click).
<a id='menu_1 onclick='return MenuItem_Click(this);'>Click Me!</a>
<script type="text/javascript">
function MenuItem_Click(me) {
alert(me.id); // The Id of menu clicked.
// Do Whatever you want with the id now.
.
.
.
}
</script>
2- Logging clicked menu id
You have 2 options actually ... use a web-service call each time a menu clicked (which I don't recommend)
OR
Use a variable to store the clicked menu ids Or a hidden variable.
<script type="text/javascript">
function MenuItem_Click(me) {
var hdnMenuLog = document.getElementById('hdnMenuLog');
hdnMenuLog.value = hdnMenuLog.value + '|' + me.id;
}
</script>
Hope this helps!
You can not access javascript variable value in server side code until you do postback and send asnc call using ajax. Asp.net generates html and javascript code from server side and sends response to client i.e. browser.
To access javascript variable value after postback you can assign it to some hidden field that is made server accessible and access it on server side code. This is how asp.net maintains ViewState.
I tried
<asp:Label CssClass="helperLabel" runat="server" Visible="False">Test</asp:Label>
<script type="text/javascript">
function MenuItem_Click(item) {
// Setup
$(".helperLabel").html("asdf");
<%
MyAspLogger("Clicked on item");
%>
</script>
in code behind I have
protected void MyAspLogger(string logMessage)
{
MyLogger.Debug(logMessage + "/" + helperLabelId.Text);
}
It's working fine but 2 other issue.
Text is not change on server side but only on client side(saw that after removed Visible attribute from asp control).
And also I found that MyAspLogger method is called on page load not after click event.
What I need is grabb itemId and log that via my Logger method from code behind.
Thank you.

Setting Scroll Position on PostBack

I am writing in asp.net c# code.
I want to control the page position on a post back. Neither MaintainScrollPositionOnPostback equal true or false, is what I want. True is too low and False is too high. Another problem is that the position should be different depending on which control is press. A third issue is that MaintainScrollPositionOnPostback=true works in I.E. but not in Firefox.
Want I want is similar to the href related tags e.g. <a href="#body2"> except in code.
Thanks for any suggestions.
Assuming you are able to use JQuery, try the following:
http://abeautifulsite.net/blog/2010/01/smoothly-scroll-to-an-element-without-a-jquery-plugin/
Just inject script and pass the ID of the control that fired your postback event.
If you cannot use jquery for some reason, here is a less elegant approach:
http://clifgriffin.com/2008/10/14/using-javascript-to-scroll-to-a-specific-elementobject/
Edit (Samples):
Here is an example of straight html using the jquery method, presuming you have a script file named jquery.js in the same folder as the html page.
<html>
<head>
<script type='text/javascript' src='jquery.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
$('html,body').animate({
scrollTop: $('#scrollHere').offset().top
}, 0//increase for smooth, visible scroll
);
});
</script>
</head>
<body>
<div style='width:100px; height:1000px; background-color:red;'>
top filler
</div>
<a id='scrollHere' href='#'>Scrolls to this element</a>
<div style="width:100px; height:1000px; background-color:blue;">
bottom filler
</div>
</body>
</html>
Here is an example of a client-side method that you can pass the "ClientID" property of any visible page control and it will register the javascript to scroll to the element on page load (assumes jquery is registered on the page and only registers one call per request):
private void ScrollToControl(string controlId)
{
//scroll to button
string script =
"$(document).ready(function() {" +
"$('html,body').animate({ " +
"scrollTop: $('#" + controlId + "').offset().top " +
"}, 0);" +
"});";
if (!Page.ClientScript.IsStartupScriptRegistered("ScrollToElement"))
Page.ClientScript.RegisterStartupScript(this.GetType(), "ScrollToElement", script, true);
}
If you know specific pixel values where you want your window to be then you can try using window.scrollTo() function in Javascript.
window.scrollTo(0,0);
Maintain page scroll position on button click by:
$("#Next").click(function() { $('html,body').animate(
{ scrollTop: $('.required').offset().top
}, 0//increase for smooth, visible scroll ); });

Categories

Resources