ASP.NET and C#: hide spinning wheel when button has finished processing - c#

In my web form, I have a button, and when users click on it, I show a spinning wheel to signal that the request is being processed:
<td class="auto-style1"><asp:LinkButton ID="lblButton" runat="server" OnClick="doSomething">Button</asp:LinkButton></td>
<td id="load" style="display:none"> <img src="Images/usethiswheel.gif" height="30" width="30" /> </td>
To regulate the appearance of the spinning wheel, I am using the following snippet:
<script>
$(document).ready(function () {
$('#lblButton').click(function () {
$('#load').show();
setTimeout(function () { $('#load').hide() }, 40000);
});
});
</script>
However, I am using a timeout function expiring after 40 seconds. How can I make the spinning wheel disappear in the exact moment the button has finished processing?

use ajax calls to wait for response from server, you might need something like this (depends on type of calls you do to serverside) since its c#:
<script>
$(document).ready(function () {
$('#lblButton').click(function () {
$('#load').show();
$.ajax({
url: '#Url.Action("SomeMethod", "Somecontroller")',
type: 'GET',
cache: false,
success: function (data) {
$('#load').hide();
}
});
});
</script>

As Davit Mikuchadze says you could try to show the loading gif when using ajax to make
the request to the code-behind(e.g webmethod), then you could hide the gif in the ajax
success function.
But, you could also try to use ajaxtoolkit updatepanel and UpdateProgress control to
achieve your requirement.
About how to install the ajaxtookit control, you could refer to this article
https://github.com/DevExpress/AjaxControlToolkit/wiki/Step-by-Step-Installation-Guide.
The code example:
ASPX:
<asp:ScriptManager runat="server">
</asp:ScriptManager>
<asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1">
<ProgressTemplate>
<div class="modal">
<div class="center">
<img alt="" src="loader.gif" />
</div>
</div>
</ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div align="center">
<h1>
Click the button to see the UpdateProgress!</h1>
<asp:Button ID="Button1" Text="Submit" runat="server" OnClick="Button1_Click" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
Code-behind:
protected void Button1_Click(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(5000);
}

For this you should try as below on completion of ajax call you should hide the spinning wheel.
<script>
$(document).ready(function () {
$('#lblButton').click(function () {
$('#load').show();
$.ajax({
url: '#Url.Action("SomeMethod", "Somecontroller")',
type: 'GET',
cache: false,
success: function (data) {
$('#load').hide();
},
failure: function(response){
$('#load').hide();
},
error: function(response){
$('#load').hide();
}
});
});
</script>

Related

How to set html input text control as invisible at code behind with out using runat="server"

I want to set input tag type="text" as invisible/visible on button click event with out using runat="server"
Below is what is coded
$(document).ready(function () {
SearchText();
});
function SearchText()
{
$(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "CalenderDetails.aspx/GetAutoCompleteData",
data: "{'Col3':'" + document.getElementById('txtSearch').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
</script>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
<br />
<input type="text" id="txtSearch" class="autosuggest" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" >
<ContentTemplate>
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
<br />
<br />
<asp:GridView ID="Gr
idView1" runat="server" AllowPaging="True" PageSize="20" OnPageIndexChanging="GridView1_PageIndexChanging" OnRowDataBound="GridView1_RowDataBound">
<HeaderStyle BackColor="#FFCC99" />
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="GridView1" EventName="PageIndexChanging" />
<asp:AsyncPostBackTrigger ControlID="btnSubmit" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
Code behind
[WebMethod]
public static List<string> GetAutoCompleteData(string Col3)
{
List<string> result = new List<string>();
if ((dtClone != null) && (dtClone.Rows.Count > 0))
{
DataRow[] foundRows;
string expression = "Col3 LIKE '%" + Col3 + "%'";
// Use the Select method to find all rows matching the filter.
foundRows = dtClone.Select(expression);
for (int i = 0; i < foundRows.Length; i++)
result.Add(foundRows[i][2].ToString());
}
return result;
}
If I use runat="server" I am able to make it visible/invisible but then ajax call will not perform for search operation
Can any body tell how to overcome this problem?
You are having difficulty to get two things working together which is runat="server" and making ajax call on same textbox.
You can use ClientIDMode="Static" which will not change id of textbox and you will be able to send ajax call.
<asp:TextBox ID="txtSearch" ClientIDMode="Static" runat="server"></asp:TextBox>
you could use jquery and use the following code,
function clicked(){
console.log("sf"+$("#grand").css("visibility"))
if($("#grand").css("visibility")=="visible"){
$("#grand").css("visibility","hidden");
}
else{
$("#grand").css("visibility","visible");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="hello" id="grand">
<input type="button" value="hide/show" onclick="clicked()">
Firstly, if you really dont want to add runat="server" to your button.
it is correct you can apply Web Method to the Server side,
and in the client side, you can apply AJAX to call your web method.
To achieve hiding the HTML control in the server side,
You can try apply ScriptManager and Jquery, by adding this to the Web Method.
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "clientScript", "$(':text').toggle()", true);
in case of hiding/showing type="text" without condition, it is okay to use toggle.
Otherwise you may implement your required condition and call
$(':text').show()
or
$(':text').hide()
for showing and hiding your controls on the form.

Third asp.net button doesn't open a jQuery dialog

I have a very basic testing asp.net web application. There is one <asp:Button> that pops a jQuery dialog. In this dialog there is another <asp:Button> that makes a <div> tag visible, and in this <div> tag there is a third <asp:Button>. So far everything is okay.
Now according to my code the third button should pop a second jQuery dialog, but this never happens. Where am I mistaking?
Here is my aspx code:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<asp:Button ID="btn" runat="server" Text="btn" />
<div id="div1">
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<table>
<tr>
<td>
<asp:Button ID="btn1" runat="server" Text="btn1" OnClick="btn1_Click" />
</td>
<td>
<div id="div2" runat="server" visible="false">
<asp:Button ID="btn2" runat="server" Text="btn2" />
</div>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<div id="div3" style="display:none">
<h1>test</h1>
</div>
And here is the code for the jQuery:
<script type="text/javascript">
var dialogOpts = {
resizable: false,
bgiframe: true,
autoOpen: false,
width: "710px"
};
$('#div3').dialog(dialogOpts).parent().appendTo($("#form1"));;
$(function () {
$("#div3").dialog({
maxWidth: 1050,
maxHeight: 534,
width: 1050,
height: 534,
resizable: false,
autoOpen: false,
buttons: {
Cancel: function () {
$(this).dialog("close");
}
}
});
$("#btn2").click(function () {
$("#div3").dialog("open");
return false
});
});
</script>
<script type="text/javascript">
var dialogOpts = {
resizable: false,
bgiframe: true,
autoOpen: false,
width: "710px"
};
$('#div1').dialog(dialogOpts).parent().appendTo($("#form1"));;
$(function () {
$("#div1").dialog({
maxWidth: 1050,
maxHeight: 534,
width: 1050,
height: 534,
resizable: false,
autoOpen: false,
buttons: {
Cancel: function () {
$(this).dialog("close");
}
}
});
$("#btn").click(function () {
$("#div1").dialog("open");
return false
});
});
</script>
It is placed in the body and so far only the first jQuery pops up.
And this is my c# function that makes the second <div> tag visible:
protected void btn1_Click(object sender, EventArgs e)
{
div2.Visible = true;
}
visible = false
essentially prevents element from rendering. If you register the onclick event for the unrendered (UNRENDERED, not display:none nor visibility:hidden, your button does not physically reside in the page), the onclick event does not register to anything at all. After you show your button in the update panel, there is nothing to be run on click, because no click handling has been set (the button did not exist in the time of
$("#btn2").click(function () {
$("#div3").dialog("open");
return false
});
)

asp.net button works once and then stops working

I have a imagefield that only works once as first time it displays messagebox but when I close messagebox using cancel button , here is how I am
<script type="text/javascript">
$(document).ready(function() {
$('#<%= imagebutton1.ClientID %>').click(function() {
alert('hello'); // ONLY WORKS once
$.blockUI({message: $('#mainInsert')});
});
$('#<%= Button2.ClientID %>').click(function() {
$.unblockUI();
});
});
</script>
Here is how I definsedh my image button
<br />
<asp:ImageButton ID="imagebutton1" runat="server" ImageAlign="Right" ImageUrl="/_layouts/n.png" />
<br />
<br />
Here's cancel button code,
<div id="mainInsert" style="display: none; cursor: default">
<asp:Button ID="Button2" Text="Cancel" runat="server" CssClass="rightButton" />
</div>
You may be bubbling through to other events. Be sure to stop propogation through the click events of the parents and children.
<script type="text/javascript">
$(document).ready(function() {
$('#<%= imagebutton1.ClientID %>').click(function(event) {
alert('hello'); // ONLY WORKS once
$.blockUI({message: $('#mainInsert')});
event.stopPropagation();
});
$('#<%= Button2.ClientID %>').click(function(event) {
$.unblockUI();
event.stopPropagation();
});
});
</script>
I am not certain that will solve it, but that seems to be a good first shot.
Joey
Instead of this,
$('#<%= imagebutton1.ClientID %>').click(function() {
I used onclick and put code in custom JS function to make it work, as on postback it was losing events attached to controls.

How can c# codebehind fire JavaScript code?

I have some JavaScript code that will display a modal dialogue box asking the user to wait while it runs a web service that could take several seconds to run. What cannot figure out is how to launch the JS code from my C# code running in the server. Here is the scenario:
1) User clicks asp:Button code that launches server code.
2) Server code [somehow] fires a browser event that launches the JS code that calls the web service
The JS code looks like this:
<form id="form1" runat="server">
<div>
<script type="text/javascript">
$(function () {
$('#btn_BeginProcessB').click(function (event) {
event.preventDefault();
var $Seconds = $("INPUT[id*='txtSeconds']").val();
var $Message = $("INPUT[id*='txtMessage']").val();
var $WorkingMessage = $('#WorkingMessage');
$WorkingMessage.text($Message);
var $this = $(this);
var $Loader = $('#Loader');
// show loading indicator
$Loader.show();
$("body").css({ background: "#C8C5C5" });
// Begin process
$.ajax({
type: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ Seconds: $Seconds }),
url: 'SimpleWebService.asmx/LongRunningProcess',
error: function (xhr, textStatus, errorThrown) {
alert('Error! ' + errorThrown);
// show button
// hide loading indicator
$Loader.hide();
},
success: function (data) {
alert("Data:" + data.d);
// show button
// hide loading indicator
$Loader.hide();
$("body").css({ background: "#FFFFFF" });
}
});
});
});
</script>
<script type="text/javascript">
function LoadPageWorking() {
var $Seconds = $("INPUT[id*='txtSeconds']").val();
var $Message = $("INPUT[id*='txtMessage']").val();
var $WorkingMessage = $('#WorkingMessage');
$WorkingMessage.text($Message);
var $data = JSON.stringify({ Seconds: $Seconds });
PageWorking('Loader', 'SimpleWebService.asmx/LongRunningProcess', $data, PageWorkingSuccess, PageWorkingError);
};
function PageWorkingSuccess(data) {
$("SPAN[id*='lblResult']").html("<br /><b>Result:</b>" + data.d + "<br />");
$('body').css('background', originalBackground);
};
function PageWorkingError(xhr, textStatus, errorThrown) {
alert('Error! ' + errorThrown);
$('body').css('background', originalBackground);
}
</script>
<!--- HTML --->
<div id="Page">
<h1>
Long Running Process Test Page</h1>
<p>
This site demonstrates how to invoke a long running process and let the user know
that the process is underway. When the button is clicked, it calls a web service
that sleeps for the designated number of seconds and returns a message.</p>
<br />
Enter number of seconds for worker process to sleep:
<asp:TextBox ID="txtSeconds" runat="server" Width="25" Text="3" /><br />
Enter the message to be displayed while the process is working:
<asp:TextBox ID="txtMessage" runat="server" Text="Working...(please be patient)"
Width="300px" /><br />
<asp:Label ID="lblResult" runat="server" />
<br />
<input type="button" id="btnBegin" value="Click to test LoadPageWorking function"
onclick="LoadPageWorking();" />
</div>
<div id="Loader">
<center>
<span id="WorkingMessage">Default Loader Message</span>
<div class="ProgressBar-Animated">
</div>
</center>
</div>
</div>
</form>
What code can I write in my C# event that will fire the LoadPageWorking() JS function?
Even if you have a server side button control, you can use it's onclientclick property to call javascript directly. But if you have to call the script from code behind, you can use ClientScriptManager.RegisterStartupScript() or ClientScriptManager.RegisterClientScriptBlock() based on your requirement. There are plenty of examples out there.
Have the button trigger a page working function that creates some indicator that you are working, fire off the ajax request, and when it comes back finish the working and hide the indicator. No need to ever have to go to code behind.
Why don't you have your LoadPageWorking() start the server, then show the JS modal popup? You can have your popup poll your service to determine if it's completed, and hide itself when it is.
You should try using the RegisterClientScriptBlock method. It will allow you to dynamically add script sections to your page's source. You can include any Javascript you'd like, including invocation of a method already defined in the page.

jQuery UI's Dialog doesn't work on ASP.NET

I have the following test ASPX page:
<head runat="server">
<title></title>
<script src="js/jquery-1.2.6.min.js" type="text/javascript"></script>
<script src="js/jquery-ui-1.6.custom.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
var dlg = $("#dialog").dialog({
bgiframe: true,
autoOpen: false,
height: 300,
modal: true,
buttons: {
'Ok': function() {
__doPostBack('TreeNew', '');
$(this).dialog('close');
},
Cancel: function() {
$(this).dialog('close');
}
},
close: function() {
dlg.parent().appendTo(jQuery('form:first'));
}
});
});
function ShowDialog() {
$('#dialog').dialog('open');
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="TreeNew" runat="server" Text="New"
OnClientClick="ShowDialog();return false;" onclick="TreeNew_Click"/>
<asp:Label ID="Message" runat="server"></asp:Label>
<div id="dialog" title="Select content type">
<p id="validateTips">All form fields are required.</p>
<asp:RadioButtonList ID="ContentTypeList" runat="server">
<asp:ListItem Value="1">Texte</asp:ListItem>
<asp:ListItem Value="2">Image</asp:ListItem>
<asp:ListItem Value="3">Audio</asp:ListItem>
<asp:ListItem Value="4">Video</asp:ListItem>
</asp:RadioButtonList>
</div>
</div>
</form>
</body>
</html>
I use dlg.parent().appendTo(jQuery('form:first')); on close function to retreive the values from RadioButtonList.
It works well but before the page do the PostBack the div "Dialog" moves below the New button. Why?
I think that this is caused because you are calling:
dlg.parent().appendTo(jQuery('form:first'));
at the close callback. This will move the dialog. Why don't you call this immediately after creating the dialog?
try chaning
$(function() {
to
$(document).ready(function() {
also check where it fails with some sort of javascript debugger opera got builtin and FireFox got FireBug..

Categories