show loading image using c# code behind - c#

I am working on a web application where I want to show a loading image (busy indicator) when my code create a xml file and download it I want to show the image in a div. I should use c# code only not update panel nor the jquery ajax technique. My code looks like:
protected void lb_DownloadXML_Click(object sender, EventArgs e)
{
this.imgLoading.Visible = true;
//all my code
this.imgLoading.Visible = false;
}
my image is
<img src="Images/loading_big.gif" width="50" height="40" runat="server" id="imgLoading"
visible="false" />
but its not working. Can anybody explain me how can I achieve this task.
thanks in advance.

To execute server side code from client machine, there is no other way other than UpdatePanel or Ajax. The client request should reach to the server to execute the request. And the way this happens is by PostBack or by Get request. PostBack will reload page, if you are not using UpdatePanel (I guess which you don't want) and second is GET, which again you don't want.
Update
According to #Lloyd
Yes it is possible, you can render contents to the page sequentially by setting the "Response.BufferOutput" property to false, writing directly to the Response.Output and Flushing the stream.

You should well understand that when you write any code on server side it is only reflected in the broswer after a successful postback. Over here if you write C# code to display an progress image then it would be displayed only after the postback is successful, that means after your XML file has been created and downloaded to the client end or after successful execution of lb_DownloadXML_Click().
So there is no way to achieve that using C# server side code, you have to rely on client side programming to achievev this.

Related

How to call javascript function and c# code on asp:button?

When a user clicks a button on ASP.net page, I need to
Save file from asp:fileUpload in a folder on a server - I guess this needs to be done in C#, like in How to correctly use the ASP.NET FileUpload control
Run a javascript function like in How to call javascript function from asp.net button click event
Is there a way to combine C# and Javascript to achieve what I need? If not, how should I do it?
Try using the onClientClick property of the asp:button element.
Ex, on your .aspx file:
<script type="text/javascript">
function myFunction()
{
alert('hi');
}
</script>
...
<asp:button id="Button1"
usesubmitbehavior="true"
text="Open Web site"
onclientclick="myFunction()"
runat="server" onclick="Button1_Click" />
And in your code behind (.aspx.cs)
void Button1_Click (object sender, EventArgs e)
{
if (this.FileUpload1.HasFile)
{
this.FileUpload1.SaveAs("c:\\" + this.FileUpload1.FileName);
}
}
More info at
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.onclientclick.aspx
Note that no JavaScript actually "runs" until the server-side code (C# in this case) has entirely completed and the resulting page is returned to the client. Once that page renders on the client, then JavaScript runs on the client.
So in order to execute your JavaScript code, all you need to do is include it in the page being returned to the client. There are a number of ways to do this, and the options depend on whether you're using WebForms or MVC.
You might use something like RegisterStartupScript in WebForms, for example. Or, you could just have the JavaScript code exist in a PlaceHolder control with Visible=false and only make the control visible in the response which intends the JavaScript code to run. (Roughly the same method is also easily usable in MVC by just wrapping the JavaScript code in a server-side condition to determine whether to render it or not.)
The main thing to remember is that you're not "running the JavaScript code from C#" or anything like that. There's a hard separation between server-side and client-side code. The server-side code ultimately builds the page that it sends back to the client, and that page can include JavaScript code to run on that client.

Javascript confirm box in C# code behind

I am trying to show a javascript confirm box in the middle of some server side code and after getting user confirmation continue processing but confirm box does not show up. I even wrote some sample code but no success.
after some server processing I need to ask user a question and after user confirmation continue some other server code. it seems to be very simple. even alert box work. How can I solve it?
please note that I can not call javascript confirmbox straight from buttonclick I need to do some serverside code and if that was ok then I want to show a confirmbox for continuation.
here is the code
<asp:Button ID="btn_deletefromDB" runat="server" OnClick="btn_deletefromDB_Click" Text="Delete from Datatbase);" />
protected void btn_deletefromDB_Click(object sender, EventArgs e)
{
//Delete service from Database
// some server side processing code
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "confirm", "return confirm('Do you want to delete it from runtime too? Click OK to proceed.');", true);
Label1.Text = "delete from runtime confirmed";
// continue and delete from runtime
//bla bla bla
}
Instead of triggering this in the code-behind, you should add it to the Button1 OnClientClick event like so:
<asp:Button ID="Button1" runat="server" OnClientClick="return confirm('Do you want to delete it? Click OK to proceed.');" OnClick="Button1_Click" />
Web applications do not work like this. You cannot ask for user input in the middle of page's server-side life-cycle. This question has to be asked client-side and user's response has to come to the server as part of the page's submitted data.
All ScriptManager.RegisterStartupScript does is contributes to the final html content that will be sent to the client when the page completes request processing. Keep in mind that by the time this html content arrives to client computer the user may have closed the browser and gone home.
Use AJAX to submit query to server and make the server code so that it does it’s processing in two parts. I don’t have any working examples of this but this is how it would work in general. For posting data to server you can use native AJAX objects in JS or any other library as others suggested and for processing data on the server side you can use generic handlers (ashx) instead of standard web pages.
Send request to the server.
Catch the first part of the processing via JS on the client page.
Show JS window
Submit the other part to server
You’ll have to send results of the first part of processing back to the client because server will not be able to connect second request with the first one by default.

Trying to take user input and write to a file

i'm having a problem where I am trying to save the geolocation of an address unto a file. I am using hidden labels to transfer the information.
on the client side button event I have:
function save() {
document.getElementById("hidLat").value = y;
document.getElementById("hidLon").value = x;
<% saveAddress s = save(); %>
}
and in c# I have:
protected saveAddress save()
{
saveAddress s = new saveAddress();
s.latitude = hidLat.Value;
s.longitude = hidLon.Value;
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"C:\\savedAddresses.txt", true))
{
file.WriteLine(s.latitude + " " + s.longitude);
file.Close();
}
return s;
}
When I click on the button the file is created but nothing is saved into it.
Am I doing this right or is there a better way to try and write the user input into a file?
I think you're getting confused on the web lifecycle. In your particular instance, this is what is happening:
Your page is requested, and the ASP.NET Runtime loads your code behind and attempts to execute the page.
In the process of executing your page, the ASPX contains code to call
saveAddress s = save()
In this way, that method is called before the page is even rendered back to the client.
When the page is finally sent down to the client, you have some client side code invoking function save().
Im guessing you want that server side method to be invoked after the javascript function has run. You have two options:
Full PostBack - You post the form back to the server, and your ASPX code behind can have some code there to inspect Page.IsPostBack and attempt to call your server side method.
Ajax - You can make an ajax request to a specific handler on your site and then invoke your server side save method.
Are you sure the latitude and longitude variables are set? Try printing them out first..
Code seems OK
It appears you are confused about about transferring values between server and client code. Seeing the markup would be useful. I am assuming you are using webforms <asp:Label /> control. In order to transfer values to the server you need to post a form or make an XMLHttpRequest. There are other ways but we will just stick with these two for now.
Also remember that if these labels are server controls their values are stored in viewstate. Modifying the value with javascript will not affect the view state. I would recommend storing the values in a hidden form input field. Add your save logic to a save OnClick server side.
Comment
You don't want to use
file.Close();
when you use "using(){}"

ASP.NET - Display Message While Page Is Loading

I have a page that performs a long-running task (10 to 15 seconds) in the page_load method.
I have client-side javascript code that will display a decent "page loading" animated gif to the user.
I am able to invoke the JavaScript method from the code-behind, to display the "page loading" animated gif, however, the long-running task is hanging up the UI such that the animated gif doesn't actually display until after the long-running task is complete, which is the exact opposite of what I want.
To test this out, in my page_load method I make a call to the JavaScript method to display the animated gif. Then, I use Thread.Sleep(10000). What happens is that the animated gif doesn't display until after Thread.Sleep is complete.
Obviously I am doing something incorrect.
Any advice would be appreciated.
Thanks.
Chris
Below is an example of the code-behind:
protected void Page_Load(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript
(GetType(), "Javascript", "javascript: ShowWaitIndicator(); ", true);
Response.Flush();
Thread.Sleep(10000);
}
I accomplished this by placing a timer on the page. After its first tick disable it and run your task.
<asp:Timer runat="server" id="UpdateTimer" interval="500" ontick="UpdateTimer_Tick" />
I placed this within an UpdatePanel for my needs. I'm not sure what will work best for you. Then in your code behind...
Protected Sub UpdateTimer_Tick(ByVal sender As Object, ByVal e As EventArgs)
UpdateTimer.Enabled = False
' run method here
End Sub
The reason is that the Page.Load event fires before any response has been sent to the client; so any instructions for the client (such as executing your javascript) doesn't occur until the client receives the response.
So... placing the long-running task in Page.Load won't have the effect you want. This sounds like a case for using AJAX or some other form of asynchronous data-retrieval. In this scenario the page you return to the client doesn't containt he result of your long-running task--so the page itself (with it's spinner) loads quickly, then the client requests the data; when the data is ready (10-15 seconds later) you can update the DOM in the client with the results.
Following example will work for you. just place in Page Load Event.
Response.Write("<div id=\"loading\" style=\"position:absolute; width:100%; text-align:center; top:300px;\"><img src=\"http://www.cse.iitk.ac.in/users/singhroh/images/loading.gif\" border=0></div>");
Response.Flush();
System.Threading.Thread.Sleep(5000);
Response.Write("script>document.getElementById('loading').style.display='none';</script>");
I would avoid invoking your JavaScript from the code-behind.
Instead, utilize the jQuery library. You can trigger your code to be called immediately after the DOM is loaded by using the following code:
$(document).ready(function() {
//Call your JavaScript method here.
});
You'll also need to add jQuery to your page, which is a single script include from the Microsoft CDN. Add this to your markup to do this:
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js"></script>
This will call your GIF JavaScript method immediately when the page is loaded and you can eliminate your Thread.Sleep. I'm assuming your animated GIF method automatically hides the image after 10-15 seconds.
Taking it old school, you could switch buffering off. With buffering on (the default), the page is generated in it's entirity before it's sent to the client. If you switch buffering off, it's sent as it's loaded, so you can send the html to switch the loading graphic on, do your long running task, then send some javascript to switch it off.
It sounds like the Javascript onload is being displayed after the ASP onload processes. You may want to delay your time-intensive action to Page.LoadComplete - this way, your user will see the Javascript render before the intensive operation occurs.
Then, you would update the page contents as needed after the function completes.
Can you provide an example of the code?

Run javascript function after Server-Side validation is complete

Ok, I've got a lightbox with a small form (2 fields) in it, inside an UpdatePanel, and I want to close this lightbox (must be done via javascript) when the 'Save' button is pressed.
However, there is a need to have a server-side CustomValidator on the page, and I only want to close the lightbox if this returns as valid.
Does anyone know a way to trigger javascript (or jQuery) code from a server-side validator?
You can add a little snippet of code using the ScriptManager to execute after the response comes back to the UpdatePanel.
if (Page.IsValid){
ScriptManager.RegisterStartupScript(
customValidator1,
typeof(MyPageClass),
"closeBox",
"myLightBoxVariableOnThePage.close()",
true);
}
When that server side validator runs, it will send a whole new page to the browser. Anything that was shown in the browser before was destroyed, including any state kept in your javascript. If new page bears a strong resemblance to the old page, you should consider this a happy coincidence.
Therefore, the thing to do here is rather than executing a javascript function, have your CustomValidator make the correct changes to the page on success so that it's rendered to the browser correctly in the first place.

Categories