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.
Related
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>
I am trying to make a button on the webpage that executes some code and I can't get the button to execute anything
The code in the .cshtml page:
<div>
<input type="button" value="Check for new Scenarios" onclick="NewScenario_Click" />
</div>
The code in the .cshtml.cs page:
void NewScenario_Click(Object sender, EventArgs e)
{
Console.WriteLine("Test");
}
You'll have to setup either a javascript listener (or Jquery or something else clientside) that calls an AJAX request to route to server side code.
something like this might work:
Change the input to:
<div>
<input type="button" id="newScenario" value="Check for new Scenarios" onclick="NewScenario_Click"/>
</div>
And then make a new javascript script that does something similar to the following (I'm using Jquery on this BTW)
var button = $('#newScenario');
button.on('Click', function(){
$.ajax({
url: 'PATH_TO_SERVER',
type: 'GET',
success: function(data){
alert("button pressed!");
},
error: function(request, error){
alert("Request: "+JSON.stringify(request));
}
});
});
I've an image uploader in a project and uploading images with Ajax that works perfect. It shows uploaded images instantly without page refresh. Here is the code that I am using to upload images:
<script>
$(function () {
$('#btnUpload').click(function () {
var fileUpload = $("#FileUpload1").get(0);
var files = fileUpload.files;
var test = new FormData();
for (var i = 0; i < files.length; i++) {
test.append(files[i].name, files[i]);
}
$.ajax({
url: "../UI/Upload.ashx",
type: "POST",
contentType: false,
processData: false,
data: test,
success: function (result) {
alert(result);
//This section refreshes the div with uploaded images and shows images without full page refresh
$('#divImages').load(document.URL + ' #divImages');
},
error: function (err) {
alert(err.statusText);
}
});
});
});
</script>
<input type="file" id="FileUpload1" />
<input type="button" id="btnUpload" value="Upload Files" />
<div id="divImages" clientidmode="Static" runat="server">
<asp:Label ID="labelImages" ClientIDMode="Static" runat="server"></asp:Label>
</div>
The problem is after uploading images, the images are shown in the content but unable to click the images and a 'Delete' link is associated with every image that also seems to be blocked. Then when I refresh the full page, the click on the images and links works. I am not sure why it happens? In the inspect element of the browser, I can see newly div created inside like the below:
<div id="divImages"> //The newly created div after partial refresh with Ajax every time I upload image
<div id="divImages" clientidmode="Static" runat="server">
<asp:Label ID="labelImages" ClientIDMode="Static" runat="server"></asp:Label>
</div>
</div>
Does it prevent me to click on the images/buttons or anything else? Would be grateful if it is pointed out.
This is the code I am using for deleting images with links (Basically I am using the links as button):
$('#divImages a.deleteLink').click(function () { //Ajax used to delete images from 'Images' folder with jQuery
var image = $(this).attr("img");
$.ajax({
type: "POST",
url: "../UI/DeleteImage.ashx",
data: "imageName=" + image,
contentType: 'application/x-www-form-urlencoded',
success: function (response) {
if (response == "true") {
$('#divImages a.imageLink[imgsrc*=\"' + image + '\"]').fadeOut();
$('#divImages a.deleteLink[img=\"' + image + '\"]').fadeOut();
}
},
error: function (response) {
alert('There was an error. ' + response);
}
});
});
});
The OP asked me to post this as an answer and I can't do anything about it.
See my explanation in the comments section
$('body').on('click', '#divImages a.deleteLink', function() {
In an Asp.Net application I need the jQuery progress bar that runs till the data is not saved in database
For this I created a web service and the Ajax jQuery function and the progress bar Javascript plugin
HTML
<div id="progressbar"></div>
<div id="result"></div>
<asp:Label runat="server" ID="lbldisp" Text= "Percentage Completed : "/>
<asp:Label runat="server" ID="lblStatus" />
<asp:Button ID="btnSave" runat="server" Text="Save" class="buttonstyle" />
Script (I am using Sys.Application.add_load instead of document.ready function due to DOM Interruption )
<link type="text/css" href="CSS/ui.all.css" rel="stylesheet" />
<script src="js/jquery-1.8.1.js" type="text/javascript"></script>
<script src="js/ui.core.js" type="text/javascript"></script>
<script src="js/ui.progressbar.js" type="text/javascript"></script>
<script type="text/javascript">
Sys.Application.add_load(function() {
// jquery Progress bar function.
$("#progressbar").progressbar({ value: 0 });
$("#lbldisp").hide();
//button click event
$("#ctl00_ContentPlaceHolder1_btnSave").click(function() {
$("#ctl00_ContentPlaceHolder1_btnSave").attr("disabled", "disabled")
$("#lbldisp").show();
//call back function
var intervalID = setInterval(updateProgress, 250);
$.ajax({
type: "POST",
url: "JobCard.aspx/InsertData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function(msg) {
$("#progressbar").progressbar("value", 100);
$("#lblStatus").hide();
$("#lbldisp").hide();
$("#result").text(msg.d);
clearInterval(intervalID);
}
});
return false;
});
});
function updateProgress() {
var value = $("#progressbar").progressbar("option", "value");
if (value < 100) {
$("#progressbar").progressbar("value", value + 1);
$("#lblStatus").text((value + 1).toString() + "%");
}
}
</script>
Web service
[System.Web.Services.WebMethod]
public static string InsertData()
{
fortest jobcardForm = new fortest();
//this is a line 760 --> jobcardForm.Insert_OilService();
jobcardForm.Insert_TuningService();
jobcardForm.Insert_OtherServices();
jobcardForm.Insert_QRCService();
jobcardForm.Insert_problemTaken();
jobcardForm.Insert_ActionTaken();
jobcardForm.Insert_SpareParts();
//Insert_Technician();
dsJobCardTableAdapters.Select_JobCarRegistrationTableAdapter insertjobcard = new dsJobCardTableAdapters.Select_JobCarRegistrationTableAdapter();
string a = insertjobcard.Insert_JobCarRegistration(
jobcardForm.txtdate.Text, jobcardForm.txtTimeIn.Text,
jobcardForm.txtTimeOut.Text, jobcardForm.Txt_RegNo.Text,
jobcardForm.Txt_FleetNo.Text,
jobcardForm.chkbkdvechle.Checked, jobcardForm.chkwalkin.Checked,
jobcardForm.chkRepeatJob.Checked,
jobcardForm.txtCustomerName.Text, jobcardForm.txtRiderName.Text,
jobcardForm.txtPhoneNo.Text, jobcardForm.txtEmail.Text,
Convert.ToInt32(jobcardForm.ddl_ServiceAdvisor.SelectedValue),
Convert.ToInt32((jobcardForm.ListBox1.SelectedValue == "" ? "0" : jobcardForm.ListBox1.SelectedValue)),
jobcardForm.ddl_Model.SelectedValue,
jobcardForm.ddl_type.SelectedValue, jobcardForm.txtKMSRUN.Text,
jobcardForm.ddl_color.SelectedValue
, "1", HttpContext.Current.Session["user_id"].ToString(),
jobcardForm.txtdateout.Text, jobcardForm.txtchassis.Text,
jobcardForm.ddlyear.SelectedValue, jobcardForm.txtexpirydate.Text,
jobcardForm.txtnotes.Text,
jobcardForm.ddllocation.SelectedValue).ToString();
HttpContext.Current.Response.Redirect(HttpContext.Current.Request.RawUrl);
return "Save Completed...";
}
Looks like the script is working fine but I am getting an error in the web browser console Window and the error is "500 Internal Server Error" at line 760 in web service jobcardForm.Insert_OilService();. But when I use the web service code in server side onclick event the data is inserted into the database. I need the progress bar, that's why I have to change the logic using web service
ERROR
I normally create an object of a class to use it in a static method and this was the simplest way to use a non-static method in a static method.
Why dont you do something like this:
function FunctionName() {
$.ajax({
type: "POST",
url: ,
data: JSON.stringify(),
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {
$("#progress-bar").show();
$("#progress-bar1").hide();
},
complete: function () {
$("#progress-bar").hide();
$("#progress-bar1").show();
},
success: function () {
}
});
}
And have 2 div
<div class="gap"></div>
<div id="progress-bar" style="display:none;">
<img src="~/Images/ajax-progressbar.gif" />
</div>
<div id="progress-bar1"></div>
</div>
So before you send your request you show $("#progress-bar").show(); once once the content loaded you hide it. Hope this answer your question.
I have a asp.net web forms app with update panels.
and its also in a listview and I dont know if that matters or not.
I have the following Javascript..
<script lang="javascript" type="text/javascript">
function pageLoad(sender, args)
{
$(document).ready(function () {
$('textarea.epop').live('click', test);
});
function tes(event)
{
var btn = $(this);
alert(btn.val());
$('#editortext').val(btn.val());
var dialog = $('#edialog').dialog({
modal: true,
width:'auto',
resizable: false,
buttons: {
'OK': function() {
alert($('#editortext').val());
alert(btn.val());
btn.val($('#editortext').val());
$('#editortext').val("");
$(this).dialog('close');
return false;
}
}
});
// Move the dialog back into the <form> element
dialog.parent().appendTo(jQuery("form:first"));
$('#edialog').dialog('open');
return false;
}
}
</script>
Then I have this in the html body..
<div id="edialog" title="Edit SQL" style="display: none">
<label for="editortext">
SQL Query:</label>
<textarea rows="20" cols="100" id="editortext" class="editortext"></textarea>
</div>
and then in one of my list items in my list view wich is inside a update panel. I have..
<asp:TextBox ID='txtSQLQuery' CssClass="epop" TextMode="multiline" Columns="50" Rows="5" runat="server" Text='<%# Eval("SQLQuery") %>' />
code works perfect the first time with no post back.
but say I change the selection, and then a auto postback happens...
then the code no longer sets the text.. when you click ok..
using alerts I can see that its actually still referencing the old value and not the new current displayed value which seemed to invoke the click.
At this point I am stumped..
If you have your controls inside updatepanel and the update panel is set to updatemode ="condicional" you probably have to invoke updatePanel.update() from your server side code to update values.
Another thing that often happens is that the update panel and jquery are not best friends, so it will be better writing or initialize your code like this:
$(document).ready(function () {
$('textarea.epop').live('click', function(e){
test();
});
});
// register again after postback's
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function() {
$('textarea.epop').live('click', function(e){
test();
});
})