How to load javascript function from an dynamicall added control? - c#

The Master page got a ScriptManager.
Then i got a Control with a ScriptManagerProxy and an UpdatePanel.
Inside the UpdatePanel there I dynamically add a Control (also containing a ScriptManagerProxy) and from that control I need to run some JavaScript code.
DynamicControl.ascx:
<script type="text/javascript">
function doSomething() {
alert(1);
}
</script>
DynamicControl.ascx.cs:
public void Page_Load(object sender, EventArgs e)
{
...
ScriptManager.RegisterStartupScript(
this.Page, this.GetType(), "scriptID",
"<script type='text/javascript'>doSomething();</script>", false);
My problem is that the function "doSomething()" is never called and i dont know why. :S
Edit: It is called but not directly when i add the control.
If I do code like this, there will be an alertwindow:
"<script type='text/javascript'>alert(1);</script>"
Ok I think i need to add some more information:
The control is dynamical added inside a jQuery Dialog. And I found out that the javacode is first executed after i close and then open the dialog. Some kind of event is triggered so that the code is executed there i think. Is it possible to force this event? so the scripts are executet directly when the control is added ?
placeHolder.Controls.Add(dynamicReportControl);
This c# code doesn't execute the javascript tag immediately ?

Please try something like this
ScriptManager.RegisterStartupScript(
this.UpdatePanel1, this.UpdatePanel1.GetType(), "scriptID",
"<script type='text/javascript'>doSomething();</script>", false);
Where UpdatePanel1 is your UpdatePanel

Try setting the addScriptTags argument to true, and remove the script declaration from your code.
Is that code only supposed to run on every request? If so, why not just add this code to the ASCX:
window.onload = doSomething();

Related

Script from ascx file use in ascx.cs

I have one script from ascx file to hide the popup page. This script currently use when user click cancel button.
Script in ascx file:
<script>
function HidePopup() {
$find("mpeDiscountedProducts").hide();
return false;
}
I want to use this script in ascx.cs (behind code) to hide the popup when user click on select button.
Below code that i want to place the script:
protected void btnSelect_Click(object sender, EventArgs e)
{
RemoveDiscountedItemsFromCart();
AddToCart(1);
this.Page.GetType().InvokeMember("CallFromDiscountProduct", System.Reflection.BindingFlags.InvokeMethod, null, this.Page, null);
}
Thanks.
Call
Page.ClientScript.RegisterStartupScript(
this.GetType(), "Hide_mpeDiscountedProducts", "HidePopup()", true);
Documentation
"Hide_mpeDiscountedProducts" is an arbitrary key that identifies the script so that you can avoid registering it twice if another control on the page might potentially register the same script.
Your button is going to trigger a postback so the page is going to refresh. When the page refreshes it will contain a <script> tag containing a call to HidePopup().

Execute jquery on first page visit

I have the following code on my Page_Load method:
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "$('#sd').slideToggle(200);", true);
}
This is a jQuery call to toggle the visibility of a div with the id #sd.
This seems to work only when this.Page.IsPostBack == true?
I have a simple form on that page that works as expected.
The form contains an input field that gets processed and returns the result.
That works.
However, now i would like to add an option to access the page with the (input) parameter in GET, so processsing could be done on first visit.
What is wrong and why is it not working on first visit?
I found it.
Typically, after I posted a question on line:
I moved this code
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js" type="text/javascript"></script>
<script type="text/javascript" src="js/jquery.flexibleArea.js"></script>
to after the title tag.
It seems like #sd wasn't being loaded at the time of the call.
Could anyone shed more light on this?

Does C# has any methods to execute Javascript function when button is pressed?

My situation is following:
I have OnTextChanged event handler on my aspx page, what calls TextChanged() method from code-behind. Now, I need to run a javascript script at the end of that TextChanged() method. How can I do this? Does ScriptManager have any methods what will execute the scripts only then when I change text in my textbox?
I might be a duplicate question, but I couldnt find information whether the scriptmanager has any methods that will run script immediately after registering it.
The actual problem is that, I need to put a script at the end of TextChanged() method and the script will just have to set focus from one html element to another.
You can simply send the required JavaScript in the code behind itself:
public void TextChanged(object sender, EventArgs e)
{
//...
this.ClientScript.RegisterStartupScript(this.Page.GetType(), "text_changed", "alert('Text was changed');", true);
}
This will show the alert only after TextChanged() is executed in the code behind.
If you're not inside a Page instance (e.g. static library) have such code, assuming you're in the context of a Page and not in some HTTP Module or something like that.
ScriptManager.RegisterStartupScript(HttpContext.Current.Handler as Page, typeof(Page), "text_changed", "alert('Text was changed');", true);
write below code in text changed function where you want to execute script. And put your java script function name in place where i bold text
**>ClientScript.RegisterStartupScript(this.GetType(), "Javascript","JavaScriptFunctionName()", true);**

insert javascript only on page postback

I'm sure this is fairly straightforward but i'm having trouble getting it to work. I want to add a javascript function to my page, but only when the page postsback.
So I have a button that calls some server-side code, and when it is finished and the page is re-loading I want the javascript function to be called.
Thinking about this i guess I could just add a hidden variable and set it when the button is clicked, but i think i'd rather just insert the javascript onto the page when it is loading back.
Is this possible, or even a good way to do it?
Thanks,
Neil
Edit: Okay this is my OnClick method in the C# code.
protected void Save(object sender, EventArgs e)
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "<script type=\"text/javascript\">alert('hello world');</script>");
EnforcementMatch(false);
EnforcementMatch(true);
ApplicationNotMatch();
ApplicationMatch();
Response.Redirect(Request.Url.ToString());
}
Another Edit: Just realised that the response.redirect at the bottom reloads my page cancelling out the code I put in, duh!
You can use ClientScriptManager.RegisterClientScriptBlock
http://msdn.microsoft.com/en-us/library/btf44dc9.aspx
If you place it on the button click event, you don't have to worry if it's a postback or not.
You know about the IsPostBack function, right?
IsPostBack (MSDN)
if (IsPostBack)
{
ClientScript.RegisterClientScriptBlock()
}
This script will be fired with every single postback from updatepanel
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function () {
alert('hello world');
});
</script>
Place it in a separate script block, only to be rendered on postback.
<script type="text/javascript" runat="server" visible="<%#this.IsPostBack %>">
TheCode();
</script>

RegisterStartupScript doesn't appear to be working on page postback within update panel

OK - so am working on a system that uses a custom datepicker control (I know there are other ones out there.. but for consistency would like to understand why my current issue is happening and fix it).
So its a custom user control with a textbox and on Page_PreRender does this:
protected void Page_PreRender(object sender, EventArgs e)
{
string clientScript = #"
$(function(){
$('#" + this.Date1.ClientID + #"').datepicker({dateFormat: 'dd/mm/yy', constrainInput: true});
});";
Page.ClientScript.RegisterStartupScript(this.GetType(), this.ClientID, clientScript, true);
//Type t = this.GetType();
//if (!Page.ClientScript.IsStartupScriptRegistered(t, this.ClientID))
//{
// Page.ClientScript.RegisterStartupScript(t, this.ClientID, clientScript, true);
//}
}
Ignore commented out stuff - that was me trying something different - didn't help.
My issue is that this all works fine when I load the page. But if I select something from a dropdownlist causing a page postback - when I click into my date fields they stop working. As in I should be able to click into the textbox and a nice calendar control appears. But after postback there is no nice calendar control appearing!
It's currently all wrapped (in the hosting page) inside an update panel. So I comment out the update panel stuff and the dates are working after page postback. So it appears to be something related to that update panel.
Any suggestions please?
Thanks!!
Have you tried ScriptManager instead of Page.ClientScript? I looked at some code that I'd written before with UpdatePanels and jQuery and I'd used ScriptManager. I think that the script is not available during a partial postback if it is not registered with the ScriptManager.
Looks like this:
ScriptManager.RegisterStartupScript(Page, this.GetType(), "DatePickerScript", clientScript, true);

Categories