I have the following structure on a usercontrol that is loaded by a page (Parent UC):
<UpdatePanel>
<UpdatePanel>
.. In the codebehind, it loads a Child user control at runtime
</UpdatePanel>
</UpdatePanel>
The UC has OnPageLoad registers a script.
ScriptManager.RegisterStartupScript(this, typeof(Page), "Load_" + this.ClientID, base.GetRegisterScript(this.ClientID), true);
The JS function never gets executed on async postbacks. If i remove the UpdatePanels, it works as expected
EDIT: Used this.GetType() instead of typeof(Page) but no luck
EDIT Again:
Matt - I tried to replace the typeof(Page) with the UC name. Here's the updated line:
ScriptManager.RegisterStartupScript(this, typeof(TemplateAreaTypeOne), "Load_" + this.ClientID, "...JS function here,,", true);
To clarify, the Page loads the Parent UC that has these UpdatePanels. The ParentUC then loads the ChildUC and the ScriptManager.RegisterStartuScript is used in teh ChildUC
EDIT
The markup has:
<script type="text/javascript">
//<![CDATA[
; findControl('PageLoadedHiddenTxtBox').value ='Set';OnLoadBegin('ctl00_WorkSpaceContent_ctlUnion1_ctlUnion1Child','Edit');OnLoadEnd('ctl00_WorkSpaceContent_ctlUnion1_ctlUnion1Child','Edit');
document.getElementById('ctl00_WorkSpaceContent_informationSummary').dispose = function() {
Array.remove(Page_ValidationSummaries, document.getElementById('ctl00_WorkSpaceContent_informationSummary'));
}
//]]>
</script>
Note that the functions that are called are the OnLoadBegin and OnLoadEnd that have been added to the HTML
EDIT AGAIN
Got it to work using:
ScriptManager.RegisterStartupScript(this.Page, typeof(Page),....)
Not sure why it works when I use the reference to the Page.
Will this work if I have multiple controls on the Page?
Why does it work when I use a reference to the page?
your registerstartupscript needs to target the control NOT the page dont use typeof(Page)
Related
I have a popup in my page which I am trying to show on dropdownlist selected index changed event.
Here is register statement
ClientScript.RegisterClientScriptBlock(GetType(),"id", "ShowApplicationPopUp()",true);
Here is my javascript function
function ShowApplicationPopUp() {
$('#NewCustomerMask').show("slow");
$('#NewCustomerApplicationPopUp').show("slow");
}
Both of my divs are initially hidden by using display:none; statement.
The problem is when my dropdownlist is changed the popup is not seen at all.I tried putting an alert statement to check if the function is called , and the alert statement is fired.Any ideas as to what I am doing wrong.
Any suggestions are welcome.
Thanks.
When you use RegisterClientScriptBlock the Javascript code is inserted early in the page, so it will run before the elements are loaded.
Use RegisterStartupScript instead, which places the code at the end of the form.
I too could not get this code to work but thanks to the above I now have working code. Note, I have a linkbutton inside an Ajax Update Panel.
in my code behind aspx.cs page is:
protected void OpenButton_Click(object s, EventArgs e)
{
// open new window
string httpLink = "../newWindow.aspx";
ScriptManager.RegisterStartupScript(this, GetType(), "script", "openWindow('" + httpLink + "');", true);
}
in my apsx page is first the link to jQuery source, then second the JavaScript for the openWindow function:
<script src="../js/jquery-1.10.1.js" type="text/javascript"></script>
<script type="text/javascript">
function openWindow(url) {
var w = window.open(url, '', 'width=1000,height=1000,toolbar=0,status=0,location=0,menubar=0,directories=0,resizable=1,scrollbars=1');
w.focus();
}
</script>
and the link that makes it all happen:
<asp:LinkButton Text="Open New Window" ID="LnkBtn" OnClick="OpenButton_Click" runat="server" EnableViewState="False" BorderStyle="None"></asp:LinkButton>
Im not a jQuery expert and must attribute some of this to the following blog:
https://blog.yaplex.com/asp-net/open-new-window-from-code-behind-in-asp-net/
i've added to the master page my script "myscript.js".
Then, in a content page, i would like to load myscript() at startup (body onload).
How can i do this ?
Either use
Page.RegisterStartupScript
if (!IsStartupScriptRegistered (key))
{
String script = "<script type=\"text/javascript\">" +
"alert('Hello World');</" + "script>";
RegisterStartupScript(key, script);
}
Or you could use the JQuery library and add the function call to the document.ready function
http://jquery.com/
$(document).ready(function(){
// Add your function call here
});
this will add onload client side event to the master page's body tag:
in the master page:
body id="PageBody" runat="server"
in the content page:
HtmlGenericControl body = (HtmlGenericControl)Master.FindControl("PageBody");
body.Attributes.Add("onload", "doSomething();");`
I use a ContentPlaceHolder in the master-page for this purpose. This makes it possible to include specific scripts in the <head> only when you want it.
The form has onLoad event. So use the tag in your Masterpage
Assign id and server="runnat" in master page body tag
<body runat="server" id="body_master">
Then your aspx .CS file insert below code in pageLoad event
HtmlGenericControl body = this.Master.FindControl("body_master") as HtmlGenericControl;
body.Attributes.Add("onLoad", "SessionTimeOuts();");
SessionTimeOuts() function should be defined in your .aspx file
Thank you
How register (call) jQuery function from asp.net usercontrol from codebehind file?
You can use ClientScriptManager.RegisterStartupScript(), for example:
var script = "$(function() { $('#message').fadeIn(); });";
Page.ClientScript.RegisterStartupScript(GetType(), "keyHere", script, true);
This gets rendered to the page as:
<script type="text/javascript">
$(function() { $('#message').fadeIn(); });
</script>
The script is just any JavaScript, nothing special about jQuery, just put in there whatever you would manually put in the page, since that's how it ends up.
I have an update panel on my page with some links that have onClick events that trigger a JQuery box to pop up. This works fine unless an AJAX postback has occurred. I saw some code on another post:
Page.ClientScript.RegisterStartupScript(TypeOf(Page), 'ajaxTrigger1', 'Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);', true);
Page.ClientScript.RegisterClientScriptBlock(TypeOf(Page), 'EndRequest1', 'function EndRequestHandler(sender, args){AsyncDone();}', true);
which I have used but it doesn't seem to be working. I keep getting AsyncDone is not defined. Does anyone have any ideas as to what I can do to sort the issue out please?
Details: ASP.NET 2, IIS7
Thanks in advance.
The problem is that when the updatepanel fires, it replaces a chunk of html in the dom, which means it replaces the elements that you have bound the click event to.
To bypass this look at jquery .live() or .delegate() which keeps looking for events matching the selector you provide, or if you want to bind to content every time the update panel refreshes content look that the jQuery updatepanel plug-in.
I sorted this by not using the document.ready in jQuery. Instead I used:
function pageLoad(sender, args) { //code }
I haven't seen any adverse effects yet so hopefully this will sort my issue.
I used update panel just only to stop the whole page refresh in asp.net which even included the jquery.But after using the update panel somewhat the problem was solved but created another problem. jquery script was not working inside the updatepanel.
This issue is now solved.
Example: In case of jquery Date picker, Usual call of Jquery script appears like this :
<script type="text/javascript">
$(function() {
$("#datepickers").datepicker({
showOn: "button",
buttonImage: "images/calendar.gif",
buttonImageOnly: true
});
});
</script>
Even I had used the same code as
Page.ClientScript.RegisterStartupScript(TypeOf(Page), 'ajaxTrigger1',
'Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);', true);
Page.ClientScript.RegisterClientScriptBlock(TypeOf(Page), 'EndRequest1', 'function EndRequestHandler(sender, args){AsyncDone();}', true);
Solution Appears here: http://kopila.com.np/
But it didnt worked for me.Later I came to know that The jquery script wont work after partial postback i.e.our ajax request.If we try to call any JQuery script inside the update panel do whatever script wont work after the first ajax request.
Example: When you are using asp.net update panel call it again as follows:
<script type="text/javascript">
function pageLoad(sender, args) {
if (args.get_isPartialLoad()) {
$("#datepickers").datepicker({
showOn: "button",
buttonImage: "images/calendar.gif",
buttonImageOnly: true
});
}
}
</script>
For More Details Go to: http://kopila.com.np
I have a textbox control Super1 in my MasterPage.
I am using javascript to access this control from my content page like this:
<asp:Content ID="ContentPage" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<script type="text/javascript">
function Somethin() {
{
document.forms[0].elements['Super1'].value = "sdfsd";
//document.getElementById('<%=Super1.ClientID%>').value = "sdfsdf";
}
}
</script>
</asp:Content>
But while page load it says Super1 not found. How can I access Super1?
In your masterpage's onload add this code :
string script = #"<script>
function Somethin() {
document.getElementById('" + Super1.ClientID + #"').value = 'sdfsd';
}
Somethin();
</script>";
if (!Page.ClientScript.IsClientScriptBlockRegistered("somethin_script_block"))
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "somethin_script_block", script);
}
this will add your script to the end of the page.
EDIT : I just realized, you use your controls ID directly in your javascript code. this may cause the exception. I update your code to fix it.
I hope this helps.
You have to make sure the document has loaded, make sure to call your functions that rely on the DOM being loaded onload. E.g.:
<script type="text/javascript">
window.onload = function() {
Somethin();
}
</script>
From the sample code you posted and since you said you are using a control, check the rendered id of the control you are trying to get at. In my experience the name is something crazy like ctl100_masterpagename_namingcontainer_controlname... that needs to show up in the js as well.
Super1 might be in a different naming container (the masterpage's control collection). You either need to render out the clientid of the control in a global javascript variable during the masterpage rendering so it can be accessed by javascript in the child page or you need to get a reference to the Masterpage, find the control there and write out the client Id in your child pages javascript...
Something like...
if the text box is in its own content place holder
var txtSuper1 = Master.FindControl("ContentPlaceHolderName").FindControl("Super1") as Textbox;
or if its not in a content place holder
var txtSuper1 = Master.FindControl("Super1") as Textbox;
3rd option might be to expose the control as a property of the masterpage (not sure) - my webforms is rusty.
On the master page, declare a javascript variable for the control, e.g:
<asp:TextBox id="Super1" runat="server"/>
...
<script type="text/javascript">
var txtSuper1 = document.getElementById('<%= Super1.ClientID %>');
</script>
It's important that you use the ClientID property, because the rendered control's ID (on the client) will be different from the server control's ID (due to naming containers).
Now you can access the textbox from javascript declared in the content pages:
<asp:Content ID="ContentPage" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<script type="text/javascript">
function Somethin()
{
txtSuper1.value = "sdfsd";
}
</script>
click me
</asp:Content>
BTW: in your code there are duplicate curly-braces in function Somethin() {{ ... }}