execute javascript after download a file (RegisterStartupScript) - javascript

I want to execute a RegisterStartupScript calling a Javascript function after certain processes happen in my code behind. It is basically a Loading loop decoration made in CSS3. I show it (with javascript) on buttons clientclick, when I know the process will take a while and I hide it when the process is finished. Everything works fine, but now I have a process in Which I download a file using another empty webform using response.redirect. The file is downloaded fine, but the RegisterStartupScript call does not work. I understand the response is the problem, but nor I need to work in a workaround to solve this (I do not want to change the whole way, cause it is implemented in many other pages and processes. I wil provide the related code (not all), in case you can give me a direct way to solve it.
Javascript
function LoadingLoopOn()
{
$('#outerAlignId').addClass("outerAlign");
$('#middleAlignId').addClass("middleAlign");
$('#innerAlignId').addClass("innerAlign");
$('#OutterCircleId').addClass("OutterCircle");
$('#InnerCircleId').addClass("InnerCircle");
$('#Loadinglbl').addClass("LoadingLabelStyle");
}
function LoadingLoopOff()
{
$('#outerAlignId').removeClass("outerAlign");
$('#middleAlignId').removeClass("middleAlign");
$('#innerAlignId').removeClass("innerAlign");
$('#OutterCircleId').removeClass("OutterCircle");
$('#InnerCircleId').removeClass("InnerCircle");
$('#Loadinglbl').removeClass("LoadingLabelStyle");
}
HTML (it is on the master page, to be able to used it in every webform)
<asp:Panel ID="outerAlignId" ClientIDMode="Static" runat="server" CssClass="outerAlign">
<div id="middleAlignId" class="middleAlign">
<div id="innerAlignId" class="innerAlign">
<div id="OutterCircleId" class="OutterCircle"></div>
<div id="InnerCircleId" class="InnerCircle"></div>
<asp:Label ID="Loadinglbl" ClientIDMode="Static" runat="server" Text="Loading..." CssClass="LoadingLabelStyle"></asp:Label>
</div>
</div>
</asp:Panel>
HTML Button Sample Where I want to used it
<asp:ImageButton ID="ExportExId" ClientIDMode="Static" runat="server" OnClientClick="LoadingLoopOn();" OnClick="ExportExId_Click" CssClass="..." ImageUrl="..." />
And the CS# Code behind
protected void ExportExId_Click(object sender, ImageClickEventArgs e)
{
//...
//Many code and DB treatment goes here, to finally get a temporally Excel file in the server
//..
//I call the page with the file name and path
Response.Redirect(String.Format("DownloadForm.aspx?FileName={0}&Path={1}", fileExported.Name, "Temp" + UserName));
//This piece of code must be excuted in its webform after the redirect (once ee finished)
ScriptManager.RegisterStartupScript(this, GetType(), "LoadingLoopOff", "LoadingLoopOff();", true);
}
As I marked in my comment, A possible solution could be AJAX. Make an ajax call to force a page update and then the function would be processed (on the load), or directly call the function through this ajax call. The problem is that I do not know how to uise AJAX in this case...
Many thanks,

Related

PageMethods Not Working with VS2013 web application

I have spent all day struggling with this Error and have read almost every article and tried every hint I found but still not able to make it work.
Please Note: EnablePageMethod=true inside ScriptManager, Method is public and static and decorated with [WebMethods]
Same coding is working all perfect with VS2010 and with empty project in VS2013 but when using with New Project -> web -> web forms the output is attached here for your reference.
Here is my code.
Code Behind:
[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
return "Hello " + name + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}
JavaScript:
<script type="text/javascript">
function ShowCurrentTime() {
PageMethods.GetCurrentTime(document.getElementById("<%=txtUserName.ClientID%>").value, OnSuccess);
}
function OnSuccess(response, userContext, methodName) {
alert(response);
}
</script>
HTML:
<div>
Your Name :
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<input id="btnGetTime" type="button" value="Show Current Time" onclick="ShowCurrentTime()" />
</div>
Try adding both [System.Web.Services.WebMethod] and [System.Web.Script.Services.ScriptMethod] to the server side GetCurrentTime method.
Also make sure your script manager has EnablePageMethods="True". Your question states you set EnablePageMethod=true which is incorrectly spelled (should be plural).
You need to fail the click event handler to prevent the postback/page submit.
Just return false from your javascript function:
function ShowCurrentTime() {
PageMethods.GetCurrentTime(document.getElementById("<%=txtUserName.ClientID%>").value, OnSuccess);
return false; // added
}
You have to make sure that the button does not post back when calling a PageMethod from client-side. With your current markup, it will post back and cause unexpected effects.
You should be using the following markup for button, so it never posts back. Then the call to pagemethod should work. In markup below the button click event is returning a false value, so the page never gets submitted i.e. posted back.
Also, it would be best if you post your page markup in full, since there may be an issue with the markup.
<input id="btnGetTime" type="button" value="Show Current Time"
onclick="ShowCurrentTime();return false;" />

Javascript not being called after an updatepanel textbox is cleared by code behind

I a web page that creates a note in a text area, On first time page load everything works fine. Meaning it goes and does a post back and writes to a database. Now , without reloading the page, on a second try if i change a drop down value and try to write to database it will not write a duplicate entry based on my code which is fine and i will clear out the note created in the text area (which is in an update panel) but for the next consecutive time if i change the drop down value, a java script that actually creates a note in the text area will not get fired and simply the text area is blank. Any help is appreciated.
<asp:UpdatePanel>
<asp:TextBox ID="txtGenVVOE" name= "txtGenVVOE" TextMode="MultiLine"
runat="server" style="font-size: 11px" rows="4" cols="44" Width="324px"></asp:TextBox></td></tr>
<tr> <td valign="top" align="center" width="50%">
<asp:Button ID="btnCopy"
class="btn" runat="server" onmouseover="this.className='btn btnhov'"
onmouseout="this.className='btn'" style="background: silvergradient" Text="COPY"
OnClientClick="ClipBoard();return false;"
ToolTip="Copy Text to ClipBoard" /> /td></tr> <end update Panel>
I have a .js script to create the note called validate() which validates the fields before creating the note
function validate() {
create_note() // which creates a note based on all the fields on the form.
}
So, as i have mentioned, this function validate is on button_click OnClientClick event and does not get called when button is clicked without reloading the page. I need some help in understanding why the scripts gets called only once on load and not on subsequent time after an postback is done to an update panel. Thanks in advance.
You will want to re-register the script in the code behind using ClientScript.RegisterStartUpScript (http://msdn.microsoft.com/en-us/library/z9h4dk8y.aspx)
In the code that causes the postback you would want to do something like this:
Dim script as string = "<script type=""text/javascript"">validate();</script>"
ClientScript.RegisterStartupScript(me,me.gettype(),"NameYourScript",script,false)
If RegisterStartupScript doesn't hit try RegisterClientScriptBlock (http://msdn.microsoft.com/en-us/library/btf44dc9.aspx )
I can't remember which one gives me trouble when it comes to update panels.

ASP.NET .aspx page: how to send extra data back via Javascript?

I have an old-fashioned ASP.NET plain .aspx page.
It has some server-side controls, some buttons to postback, etc.
I'm going to add some Javascript on the client side to create a list of extra data that the user builds.
I don't know beforehand how much of this extra data will be sent. So I can't, for example, just add 10 hidden input fields and check their values in the codebehind.
There might be 20 values sent back, there might be 100.
What's the best way to POST this extra data back to the server?
One way I can imagine it working is to add some dummy hidden list controls, to be filled in by JS on the client. It feels hacky, but I think I could make it work.
Is there a better way?
Some things to note:
I'm not using MVC or AJAX
Not using JQuery (though I could, I suppose)
I'm really just trying to get a handle on my options.
Thanks!
If it doesn't need to be POSTed via ajax you can use javascript to create the controls and then use Request.Form to retrieve the input values.
ASPX:
<script>
document.write('<input name="field1" type="text" />' +
'<input name="field2" type="text" />');
</script>
<asp:Button ID="btn" Text="button" runat="server" onclick="btn_Click" />
ASPX.CS:
protected void btn_Click(object sender, EventArgs e)
{
var keys = Request.Form.AllKeys;
foreach (var key in keys)
{
if (key.StartsWith("field"))
Response.Write(Request.Form[key]);
}
}

Unable to call a function while using master page in Javascript at checkbox checked change event

I was trying to call a function when the checkbox status changes, it calls without a masterpage. I have tried the following code:
<script type="text/javascript">
$(function () {
$('#cbOption1').on('change', PublishToPreferredZerker);
});
function PublishToPreferredZerker() {}
</script>
[...]
<asp:CheckBox ID="cbOption1" runat="server" style="text-align: left"
Text="Publish the job to particular Zerker or a group of the Zerkers." /><br />
The function is not called when using MasterPage.
Note cbOption1 is not the client ID, but the ID for the server side.
You need to do something like (Use Control.ClientID Property to get the id for HTML element):
$('#<%=cbOption1.ClientID%>').on('change', PublishToPreferredZerker);
The code
$('#cbOption1').on('change', PublishToPreferredZerker);
finds the control with id cbOption1 and then acts on that control
But when using this code on a master page, the control id does not remain cbOption1.
It is prefixed by master page content Id.
something like ct$001cbOption1
To make it work when using master pages use code like this to find the clientId for the control :
$(#"<%= cbOption1.ClientID %>").on( .... )
I got success while I added below code on Page load function.
cbOption1.Attributes.Add("onChange", "javascript:PublishToPreferredZerker()");
Javascript function
function PublishToPreferredZerker() {}
Also I have tried above answers but not get required output.
Thanks,

Referencing inline scripts from update panels in ASP.NET

I am trying to work around an issue with using inline scripts in update panels. The issue is something I might commonly solve by using Sys.Application.add_load() or creating a RegisterStatupScript() script with the ScriptManager. However, neither solution works in this case.
Here is the problem.
Update panel on asp.net (in this case, SharePoint) page:
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:Button ID="Button1" runat="server" Text="Load" />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</ContentTemplate>
</asp:UpdatePanel>
Lets say in the code behind we add a user control to the placeholder when the button is clicked.
protected void Button1_Click(object sender, EventArgs e)
{
MyControl ctrl = new MyControl();
PlaceHolder1.Controls.Clear();
PlaceHolder1.Controls.Add(ctrl);
UpdatePanel1.Update();
}
Finally, let's say our user control has some inline scripts.
<script type="text/javascript">
var myInt = 1;
alert(typeof myInt);
</script>
Putting the above together and running it would lead to an update panel that is empty (except the button) by default- get's some data added when the button is clicked that looks like the javascript above. The problem is the javascript code above will never fire.
In my real life case the user control is not terribly complex- it has a repeater that is populated when the control is loaded then some inline javascript which transforms the repeater data a bit. The data comes through but the javascript is never executed and throws no errors.
Attempted solution:
Wrap inline javascript in a function called initMyCode() then use:
ScriptManager.RegisterStartupScript(this, this.getType(), UniqueID, "initMyCode()", true);
...on the user control page load event. This fails as initMyCode() cannot be found within the page.
Anyone have a workable solution for this issue?
if(!Page.ClientScript.IsStartupScriptRegistered("initMyCode")){
string script =#"function initMyCode(){var myInt = 1;
alert(typeof myInt);}
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(initMyCode);"
ScriptManager.RegisterStartupScript(this, this.getType(), initMyCode, script, true);
}
Or
<script type="text/javascript">
function initMyCode(){
var myInt = 1;
alert(typeof myInt);}
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(initMyCode);
</script>
Have you already tried adding your code in the "ready" of jQuery?

Categories

Resources