why ajax loader image always shown using jquery and asp.net - asp.net

with asp.net code below my ajax_loader image doesn't work well and always shown ..
<asp:ScriptManager ID="MainScriptManager" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label runat="server" ID="lblname">
Name</asp:Label><br />
<asp:TextBox runat="server" ID="txbname"></asp:TextBox><br />
<asp:Label ID="lblemail" runat="server">
Email</asp:Label><br />
<asp:TextBox runat="server" ID="txbemail" /><br />
<asp:Label runat="server" ID="lblsugg">
Suggestion</asp:Label><br />
<asp:TextBox runat="server" Rows="3" Columns="20" ID="txbsugg" TextMode="MultiLine"></asp:TextBox>
<asp:Button runat="server" ID="btnsubmit" OnClick="btnsubmit_onclick" Text="submit" />
<asp:Label runat="server" ID="lblresultmsg"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
<div id="loading">
<p>
<img src="Images/ajax-loader.gif" />
Please Wait</p>
</div>
and jquery code
$("#loading").ajaxStart(function() {
$(this).show();
}).ajaxStop(function() {
$(this).hide();
});
any suggestions !?

ajaxStart and ajaxStop works only for ajax request sent by jQuery, if you use other libraries or UpdatePanel, it won't help you.
jQuery only.
Whenever an Ajax request is about to be sent {With jQuery-gdoron}, jQuery checks whether there are any other outstanding Ajax requests. If none are in progress, jQuery triggers the ajaxStart event. Any and all handlers that have been registered with the .ajaxStart() method are executed at this time.
Example of jQuery ajax request that will fire the ajaxStart and ajaxStop:
$.ajax({
url: 'foo',
...
...
});

You could create a generic way to handle this by adding the following code to a common js include. Here's a quick and dirty example:
Note: Be sure you initialize it by calling SetupGlobalAjaxHandlers on your page load.
function SetupGlobalAjaxHandlers()
{
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
}
function InitializeRequest(sender, args)
{
if(typeof(OnPageInitRequest) != "undefined")
OnPageInitRequest();
}
function EndRequest(sender, args)
{
if(typeof(OnPageEndRequest) != "undefined")
OnPageEndRequest();
}
Then, in any page that includes the js file, you could optionally implement the OnPageInitiRequest() and OnPageEndRequest() methods. There, you could show/hide your loading indicator.
I do recommend, though, that you use an UpdateProgress control as you get the show/hide logic for free.
This technique opens up some possibilities for you, say, if you wanted to disable controls while a partial postback is occurring.

Related

Asp:FileUpload and RAD ajaxmanager not working together

I have following code for uploading a file:
<asp:Panel ID="pnlCauses" runat="server">
<asp:FileUpload ID="uplCauses" runat="server" />
<asp:Button runat="server" ID="btnUplCauses" Text="Upload" OnClick="btnUplCauses_Click" />
<asp:Label runat="server" ID="lblUplCausesStatus" Text="Upload status: " />
</asp:Panel>
And i have used following code to allow only pnlCauses to refresh.
<rad:AjaxSetting AjaxControlID="btnUplCauses">
<UpdatedControls>
<rad:AjaxUpdatedControl ControlID="pnlCauses" />
</UpdatedControls>
</rad:AjaxSetting>
But seems Upload control and Ajax dont work together.
Can anyone suggest me alternatives ? That how can i allow only panel to refresh and not complete page ?
ASP.NET FileUpload cannot upload files using AJAX calls. You must force a postback request, or use a control like RadAsyncUpload to upload files asynchronously.
Telerik documentation has a workaround for older Telerik ASP.NET controls on how to disable upload button AJAX calls in a RadAjaxPanel:
<script type="text/javascript">
//on upload button click temporarily disables ajax to perform upload actions
function conditionalPostback(sender, args)
{
if(args.EventTarget == "<%= ButtonSubmit.UniqueID %>")
{
args.EnableAjax = false;
}
}
</script>
<rada:radajaxpanel runat="server" id="RadAjaxPanel1"
clientevents-onrequeststart="conditionalPostback">
<rad:radupload runat="server" id="RadUpload1" />
<asp:button id="ButtonSubmit" runat="server" text="Upload" />
</rada:radajaxpanel>

Update Panel and triggers from a repeater control

Hi I found code similiar to the following online. It's seems really great for getting a button buried in a repeater control to trigger a full cycle back to the server.
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<%=DateTime.Now.ToString() %>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="HiddenButton" />
</Triggers>
</asp:UpdatePanel>
<!--Make a hidden button to treat as the postback trigger-->
<asp:Button ID="HiddenButton" runat="server" Style="display: none" Text="HiddenButton" />
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1">
<ItemTemplate>
<!--when cick the button1, it will fire the hiddenButton-->
<asp:Button ID="Button1" Text="Trigger" CommandArgument='<%# Eval("Id") %>' OnClientClick="$get('HiddenButton').click();return false;"
runat="server" />
</ItemTemplate>
</asp:Repeater>
It uses a hiddenButton to achieve this by hooking the click event of the original button to this one. However my addition to this was the setting of the CommandArgument for the button. I would also need it to be set for the HiddenButton.
Does anyone know a way of going about this?
First I will like to explain the Disadvantage of using the Update Panel using the very same example posted by you.
Below is the Original Code
Output
To display the 22 character string you can check how much data is being received and sent to server. Just imagine following
If you would consider send each request to Database using Update Panel and your GridView is in Update Panel!!!!!!
Suppose you would use ViewState data for each request and with GridView Inside the Update Panel.
Both the above techniques are worst as per my understanding.
Now I will describe you Page Methods
Page Method over Update panel
Page Methods allow ASP.NET AJAX pages to directly execute a Page’s Static Methods, using JSON (JavaScript Object Notation). Instead of posting back and then receiving HTML markup to completely replace our UpdatePanel’s contents, we can use a Web Method to request only the information that we’re interested.
Sample Code
Output
Hope this clearly explains the difference of usage.
Answer to the original Query
You have to register the ItemDataBound event of the below Repeater and use below code for it.
Code Behind
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
Button btn = (Button)e.Item.FindControl("Button1");
btn.OnClientClick = string.Format("SubmitButton('{0}');return false;"
, HiddenButton.ClientID);
}
}
JavaScript
<script type="text/javascript">
function SubmitButton(btn)
{
$("#" + btn).click();
}
</script>
//Alternative
<script type="text/javascript">
function SubmitButton(btn)
{
document.getElementById(btn).click();
}
</script>
Reference & Here
Your HiddenButton control is a server control but you are trying to access it in JQuery using it's ASP.Net ID,
<asp:Button ID="Button1" Text="Trigger" CommandArgument='<%# Eval("Id") %>' OnClientClick="$get('**HiddenButton**').click();return false;"
runat="server" />
A quick way to fix it is to make a separate function,
<script type="text/javascript">
function SubmitButton(btn)
{
$get("#" . btn).click();
}
</script>
and change your button code to ,
<asp:Button ID="Button1" Text="Trigger" CommandArgument='<%# Eval("Id") %>'
runat="server" />
In code behind, in repeater's ItemDataBound event, find the button and HiddenControl and set Button1's OnClientClick property,
Button1.OnClientClick= string.Format("SubmitButton('{0}');return false;",HiddenButton.ClientID);

ajax update panel - imagebutton and button behaving differently?

I have an ajax panel (actually it' a Rad Ajax Panel - the behavior is similar to an Ajax Update Panel with everything in the ContentTemplate section and no Triggers), with an image button (asp:ImageButton) and a button (asp:Button).
I notice that they behave differently - the image button advances to postback (Page_Load and Button_Click server functions), when the button doesn't!
How can I achieve this behavior with the Button too? (Replacing the Button with an ImageButton solved the problem... Is there a way to maintain the Button and have the ImageButton's behavior?)
This is what my code looks like (two buttons, two click functions, and two client click functions):
<telerik:RadScriptManager ID="RadScriptManager1" runat="server">
</telerik:RadScriptManager>
<div style="width: 800px;">
<telerik:RadAjaxPanel ID="RadAjaxPanel1" runat="server" LoadingPanelID="RadAjaxLoadingPanel1">
<telerik:RadScriptBlock ID="RadScriptBlock1" runat="server">
<script type="text/javascript">
function validateSave() {
// ...
return true;
}
function validateAdd() {
// ...
return true;
}
</script>
</telerik:RadScriptBlock>
<asp:Panel ID="Panel1" runat="server" Visible="false">
<fieldset>
<legend>New item</legend>
<%--..........--%>
<asp:ImageButton ID="Button4" runat="server"
ImageUrl="~/App_Themes/ThemeDefault/images/add.gif"
OnClientClick="return validateAdd();"
OnClick="Button4_Click" />
</fieldset>
<%--..........--%>
<asp:Button ID="Button2" runat="server"
OnClientClick="return validateSave();"
Text="Save" ToolTip="Save" OnClick="Button2_Click" />
</asp:Panel>
</telerik:RadAjaxPanel>
<telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server">
</telerik:RadAjaxLoadingPanel>
</div>
UpdatePanels can often be problematic with Buttons. An easy thing that you can do is move the Button out of the UpdatePanel. After all, the more contents in your UpdatePanel, the slower the asynch postback will be.

Show "passed" image or text after validating an asp.net (req. field)validator

I have the following asp.net code:
<asp:TextBox CssClass="mf" runat="server" ID="mail1" Width="270" />
<asp:RequiredFieldValidator ID="rfv1"
runat="server"
ControlToValidate="mail1"
Display="Dynamic" />
Now I want to show an image (or text) if the validation passes on the fly (no postback)
A jQuery solution is also fine by me, but that wouldn't be so safe if javascript is disabled.
Without relying on an external framework you can tap into the ASP.Net Client Side Validation framework to handle extended/advanced functionality. In this way you are working with the framework, augmenting it instead of replacing it.
A tiny bit of JavaScript is all that is needed to enable the behavior you want.
<asp:TextBox CssClass="mf" runat="server" ID="mail1" Width="270" OnChange="showValidationImage();" />
<asp:RequiredFieldValidator ID="rfv1"
runat="server"
ControlToValidate="mail1" ClientIDMode="Static"
Display="Dynamic" >
<img src="../Image/fail.jpg" />
</asp:RequiredFieldValidator>
<img id="imgPass" src="../Image/pass.jpg" style="visibility:hidden" />
<script language="javascript">
// This function will be called whenever the textbox changes
// and effectively hide or show the image based on the state of
// the client side validation.
function showValidationImage() {
if (typeof (Page_Validators) == "undefined") return;
// isvalid is a property that is part of the ASP.Net
// client side validation framework
imgPass.style.visibility = rfv1.isvalid ? "visible" : "hidden";
}
</script>
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
Notice here that I am using a feature of ASP.Net 4 with ClientIDMode="Static" if you are not using .Net 4 then you will need to use the standard <%= rfv1.ClientID %> server side include to get at the client id inside your script.

How to check if client script is already registered during a partial postback

Below is the code I've currently implemented.
if (!Page.ClientScript.IsStartupScriptRegistered(Page.GetType(), scriptKey))
{
ScriptManager scriptManager = ScriptManager.GetCurrent(page);
if (scriptManager != null && scriptManager.IsInAsyncPostBack)
{
//if a MS AJAX request, use the Scriptmanager class
ScriptManager.RegisterStartupScript(Page, Page.GetType(), scriptKey, script, true);
}
else
{
//if a standard postback, use the standard ClientScript method
Page.ClientScript.RegisterStartupScript(Page.GetType(), scriptKey, script, true);
}
}
I'm doing as suggested in this answer so that I can register startup script on both times i.e. when there is partial postback and a full postback.
The problem is Page.ClientScript.IsStartupScriptRegistered(Page.GetType(), scriptKey) always (even when the script is registered before) returns false when it is partial postback. And I couldn't find ScriptManager.IsStartupScriptRegistered (static) method. As a result of this, additional script is emitted on all partial/async postbacks.
Please note that I'm using script manager of AjaxControlToolkit version 4.1 i.e. ToolkitScriptManager in my masterpage. But I don't thing it has something to do with this.
UPDATE
<asp:UpdatePanel ID="ContactDetailsUpdatePanel" UpdateMode="Conditional" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="UpdateContactDetailsButton" EventName="Click" />
</Triggers>
<ContentTemplate>
<div id="ContactDetailsContent" class="contact_details_content">
<div class="customer_contactdetails_left_pane">
<div class="customer_name_field">
<asp:Label ID="CustomerNameLabel" runat="server" Text="Customer" />
<asp:TextBox ID="CustomerNameValue" runat="server" />
</div>
<div class="customer_address_field">
<asp:Label ID="CustomerAddressLabel" runat="server" Text="Address" />
<asp:TextBox ID="CustomerAddressValue" runat="server" />
<asp:TextBox ID="CustomerAddressValue1" runat="server" />
<asp:TextBox ID="CustomerAddressValue2" runat="server" />
<asp:TextBox ID="CustomerAddressValue3" runat="server" />
</div>
<div class="customer_postcode_field">
<asp:Label ID="CustomerPostcodeLabel" runat="server" Text="Postcode" />
<asp:TextBox ID="CustomerPostcodeValue" runat="server" />
</div>
</div>
<div class="customer_contactdetails_right_pane">
<div>
<asp:Label ID="CustomerContactLabel" runat="server" Text="Contact" />
<asp:TextBox ID="CustomerContactValue" runat="server" />
</div>
<div>
<asp:Label ID="CustomerTelephoneLabel" runat="server" Text="Telephone" />
<asp:TextBox ID="CustomerTelephoneValue" runat="server" />
</div>
<div>
<asp:Label ID="CustomerMobileLabel" runat="server" Text="Mobile" />
<asp:TextBox ID="CustomerMobileValue" runat="server" />
</div>
<div>
<asp:Label ID="CustomerFaxLabel" runat="server" Text="Fax" />
<asp:TextBox ID="CustomerFaxValue" runat="server" />
</div>
<div>
<asp:Label ID="CustomerEmailLabel" runat="server" Text="Email" />
<asp:TextBox ID="CustomerEmailValue" runat="server" />
</div>
<div>
<asp:Label ID="CustomerWebLabel" runat="server" Text="Web" />
<asp:TextBox ID="CustomerWebValue" runat="server" />
</div>
</div>
</div>
<div class="update_button_field">
<asp:Button ID="UpdateContactDetailsButton" runat="server" Text="Update"
onclick="UpdateContactDetailsButton_Click" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
Thanks in advance.
NOTE: To be able to understand the progress on this problem, please see the comments on this answer before replying.
UPDATE
I have implemented a temporary solution to this problem by putting a check in javascript that if the script is already executing then do not execute twice. Javascript is still being spitted multiple times on every partial postback. Couldn't prevent it.
As the views to this post are increasing, I can see that there are other people who might also want answer to this problem.
If you are using this;
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "noPasswordMatch", script, true);
Then to check if it has been registered you must use this:
if (Page.ClientScript.IsClientScriptBlockRegistered(this.GetType(), "noPasswordMatch"))
if (Page.ClientScript.IsClientScriptBlockRegistered("noPasswordMatch")) doesn't work!
I ran into this same issue when writing a composite control in ASP.Net. When the control was inside an update panel Page.ClientScript.IsStartupScriptRegistered didnt work. From within the method protected override void CreateChildControls() i was doing something like
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), initializeTokenInputScriptKey, initializeTokenInputScript, true);
Hence I ran into a situation similar to what you describe here. What solved my problem was passing the control and its type instead of the page and page type to ScriptManager.RegisterStartupScript. Hence the code now looks,
ScriptManager.RegisterStartupScript(this, this.GetType(), initializeTokenInputScriptKey, initializeTokenInputScript, true);
Once I did this change I no longer needed to check Page.ClientScript.IsStartupScriptRegistered. Now my control works with or without update panels. No unnecessary js spitouts either. Hope this helps
I had implemented a temporary solution to this problem by putting a check in javascript that if the script is already executing then do not execute twice. Javascript is still being spitted multiple times on every partial postback. Couldn't prevent it.
I've written an extension method to check whether the script has already been registered with the ScriptManager. You can use the same principle to check startup scripts:
public static bool IsClientScriptBlockRegistered(this ScriptManager sm, string key)
{
ReadOnlyCollection<RegisteredScript> scriptBlocks = sm.GetRegisteredClientScriptBlocks();
foreach (RegisteredScript rs in scriptBlocks)
{
if (rs.Key == key)
return true;
}
return false;
}
Keep in mind your first line of code is the inverse of the method return value because of the !.
if (!Page.ClientScript.IsStartupScriptRegistered(Page.GetType(), scriptKey))
If IsStartupScriptRegistered is returning false as you say, then the if statement should evaluate true because of the !. This should cause the script to be registered as expected.
Your code is based on my answer here, which was based on ASP.NET AJAX 1.0 and ASP.NET 2.0. It may have something to do with .NET 3.5, although I believe I've used the above already in a newer project we did under 3.5 and it worked fine...
Can you post some markup to go with the code?
EDIT: Thanks for posting the markup.
I notice 2 things now:
You mentioned you are using ToolkitScriptManager. It is a control that inherits from ScriptManager. I didn't notice this before, but your code is still referencing ScriptManager directly. You said it was during async postbacks that the script isn't working, which leads me to believe it is an issue with your reference to ScriptManager. I've never used ToolkitScriptManager before so I can't give you exact code, but I can tell you that you'll likely need to update your code-behind, changing all references to ScriptManager and its methods/properties to the equivalent in ToolkitScriptManager.
Try adding a breakpoint on the if statement and make sure it's evaluation to true. I wouldn't be surprised if scriptManager is null, or scriptManager.IsInAsyncPostBack is false because you're using ToolkitScriptManager.
ScriptManager scriptManager = ScriptManager.GetCurrent(page);
if (scriptManager != null && scriptManager.IsInAsyncPostBack)
{
//if a MS AJAX request, use the Scriptmanager class
ScriptManager.RegisterStartupScript(Page, Page.GetType(), scriptKey, script, true);
}
Lastly - Your markup looks okay, other than you don't need the <Triggers> section. Triggers allow you to specify control which are outside of your update panel to cause partial renders. Any child control of the update panel within the <ContentTemplate> section will do this automatically. The button you are targeting in the Triggers section is already within the updatepanel. While I don't think this is the cause of your issue, I'd remove it anyway.
Hope this helps.
Did you mean this: ClientScriptManager.IsStartupScriptRegistered Method

Resources