I have a main page: Main.aspx and 2 user controls User1.ascx and User2.ascx. First, i want User2.ascx to be invisible.I have a hidden value in the main page control. And if value of hidden value is not null then show user2.ascx. I have typed the code in the prerender function on user2.ascx.
Currently, what I try
In Main.aspx
<usercontrol:User1 runat="server" ID="user1control" Visible = "false" />
By this,
In User2, it comes only in pageload event but not in OnPreRender.
I have my all code in OnPreRender
Try something like this
protected void btnToggle_Click(object sender, EventArgs e)
{
string s = btnToggle.Text;
switch (s)
{
case "Hide":
btnToggle.Text = "Show";
break;
case "Show":
btnToggle.Text = "Hide";
break;
}
ucDetails myControl = (ucDetails)Page.LoadControl("~/ucDetails.ascx");
UserControlHolder.Controls.Add(myControl);
myControl.Visible = !myControl.Visible;
}
The other option you can create this on the javascript side. Where you can wrap your usercontrol in a panel and hide and show through javascript function. Hiding and showing through css.
<script type="text/javascript">
function hide() {
document.getElementById("ResultPanel2").style.display = 'none';
}
</script>
I Solved it. I kept a hidden field in main page, and in the load event of main page, I kept a contion that if the value is not null or empty then, user2.visible = true. This worked for me.
Related
I have a button control. On click of this button I need to add a Link Button dynamically. The Link Button needs an event handler. Hence the dynamic Link button is first added in the Page_Load and cleared and added again in the button click handler. Please read Dynamic Control’s Event Handler’s Working for understanding the business requirement for this.
I have read On postback, how can I check which control cause postback in Page_Init event for identifying the control that caused the postback (inside Page_Load). But it is not working for my scenario.
What change need to be done to confirm whether the postback was caused by link button (inside Page_Load)?
Note: Refer the following for another scenario where it is inevitable https://codereview.stackexchange.com/questions/20510/custom-paging-in-asp-net-web-application
Note 1: I need to get the postback control ID as the first step inside if (Page.IsPostBack). I need to add the dynamic link buttons control only if it is a postback from the button or the link button. There will be other controls that causes postback. For such postbacks we should not execute this code.
Note 2: I am getting empty string for Request["__EVENTARGUMENT"] in the Page_Load
Related Question: By what event, the dynamic controls will be available in the Page (for using in FindControl). #Tung says - "Your GetPostBackControlId method is properly getting the name of the control that caused the postback, but it is unable to find a control with that id through page.FindControl because the linkbutton has not been created yet, and so page does not know of its existence. "
ASPX
<%# Page Language="C#" AutoEventWireup="true" CodeFile="PostbackTest.aspx.cs" Inherits="PostbackTest"
MasterPageFile="~/TestMasterPage.master" %>
<asp:Content ID="myContent" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div id="holder" runat="server">
</div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="TestClick" />
</asp:Content>
CODE BEHIND
public partial class PostbackTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(Page.IsPostBack)
{
string IDValue = GetPostBackControlId(this.Page);
int x = 0;
holder.Controls.Clear();
LinkButton lnkDynamic = new LinkButton();
lnkDynamic.Click += new EventHandler(LinkClick);
lnkDynamic.ID = "lnkDynamic123";
lnkDynamic.Text = "lnkDynamic123";
holder.Controls.Add(lnkDynamic);
}
}
protected void TestClick(object sender, EventArgs e)
{
holder.Controls.Clear();
LinkButton lnkDynamic = new LinkButton();
lnkDynamic.Click += new EventHandler(LinkClick);
lnkDynamic.ID = "lnkDynamic123";
lnkDynamic.Text = "lnkDynamic123";
holder.Controls.Add(lnkDynamic);
}
protected void LinkClick(object sender, EventArgs e)
{
}
public static string GetPostBackControlId(Page page)
{
if (!page.IsPostBack)
{
return string.Empty;
}
Control control = null;
// First check the "__EVENTTARGET" for controls with "_doPostBack" function
string controlName = page.Request.Params["__EVENTTARGET"];
if (!String.IsNullOrEmpty(controlName))
{
control = page.FindControl(controlName);
}
else
{
// if __EVENTTARGET is null, the control is a button type
string controlId;
Control foundControl;
foreach (string ctl in page.Request.Form)
{
// Handle ImageButton they having an additional "quasi-property" in their Id which identifies mouse x and y coordinates
if (ctl.EndsWith(".x") || ctl.EndsWith(".y"))
{
controlId = ctl.Substring(0, ctl.Length - 2);
foundControl = page.FindControl(controlId);
}
else
{
foundControl = page.FindControl(ctl);
}
if (!(foundControl is Button || foundControl is ImageButton)) continue;
control = foundControl;
break;
}
}
return control == null ? String.Empty : control.ID;
}
}
REFERENCE
On postback, how can I check which control cause postback in Page_Init event
Dynamic Control’s Event Handler’s Working
Understanding the JavaScript __doPostBack Function
Access JavaScript variables on PostBack using ASP.NET Code
How does ASP.NET know which event to fire during a postback?
how to remove 'name' attribute from server controls?
How to use __doPostBack()
A postback in asp.net is done by the java script function __doPostback(source, parameter)
so in your case it would be
__doPostback("lnkDynamic123","") something like this
So in the code behind do the following
var btnTrigger = Request["__EVENTTARGET"];
if(btnTrigger=="lnkDynamic123")
{
}
--- this would tell that it is your linkbutton that causes the postback
You can move the call to the GetPostBackControlId method after the LinkButton has been added to the page:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
holder.Controls.Clear();
LinkButton lnkDynamic = new LinkButton();
lnkDynamic.Click += new EventHandler(LinkClick);
lnkDynamic.ID = "lnkDynamic123";
lnkDynamic.Text = "lnkDynamic123";
holder.Controls.Add(lnkDynamic);
string IDValue = GetPostBackControlId(this.Page);
if (IDValue == lnkDynamic.ID)
LinkClick(lnkDynamic, new EventArgs());
}
}
Calling the click event handler here also more closely mimics the standard ASP.NET Page Life Cycle, where Postback event handling occurs after the Load event.
Edit:
If the control ID must be determined before the LinkButtons are created, you can create a naming scheme for the link button IDs, e.g. lnkDynamic_1, lnkDynamic_2 etc.
Request["__EVENTTARGET"] will then contain the auto-generated control ID such as “ctl00$mc$lnkDynamic_1”, which you can use to identify which LinkButton caused the postback.
If You're getting the post back control id correctly but FindControl returns nothing, then it's probably because You're using a master page. Basically, someControl.FindControl(id) searches through controls that are in someControl.NamingContainer naming container. But in Your case, the Button1 control is in the ContentPlaceHolder1, which is a naming container, and not directly in the Page naming container, so You won't find it by invoking Page.FindControl. If You can't predict in which naming container the control You're looking for is going to be (e.g. post back can be caused by two different buttons from two different content placeholders), then You can write an extension that'll search for a control recursively, like so:
public static class Extensions
{
public static Control FindControlRecursively(this Control control, string id)
{
if (control.ID == id)
return control;
Control result = default(Control);
foreach (Control child in control.Controls)
{
result = child.FindControlRecursively(id);
if (result != default(Control)) break;
}
return result;
}
}
Use it with caution though, because this method will return the first control that it finds with the specified id (and You can have multiple controls with the same id - but they should be in different naming containers; naming containers are meant to differentiate between controls with same ids, just as namespaces are meant to differentiate between classes with same names).
Alternatively, You could try to use FindControl(string id, int pathOffset) overload, but I think it's pretty tricky.
Also, check this question out.
First approach (wouldn't recommend but it's more flexible)
One completely different approach - although I don't really feel like I should promote it - is to add a hidden field to the form.
The value of this hidden field might be something like false by default.
In case of clicking one of the dynamic buttons which should cause the dynamic controls to be added again, you can simply change the hidden fields value to true on client side before performing the postback (eventually you want/have to modify the client side onclick handler to make this happen).
Of course it would be possible to store more information in such a field, like the controls id and the argument (but you can get those values as described in the other answers). No naming schema would be required in this case.
This hidden field could be "static". So it would be accessible in code behind all time. Anyhow, you might want to implement something to make sure that nobody is playing around with its values and fakes a callback which looks like it originated from one of these dynamic links.
However, this whole approach just helps you getting the id of the control. Until you create the control again, you won't be able to get the instance through NamingContainer.FindControl (as mentioned in the other answers already ;)). And in case you create it, you don't need to find it anymore.
Second approach (might not be suitable due to its contraints)
If you want to do it the clean way, you need to create your controls OnLoad, no matter if something was clicked or not. Additionally, the dynamic controls ID has to be the same as the one you sent to the client in the first place. You subscribe to its Click or Command event and set its visibility to false. Inside the click event handler, you set the senders visibility to true again. This implies, that you don't care if that link is created but instead just don't want to send it to the client. The example below only works for a single link of course (but you could easily modify it to cover a whole group of links).
public void Page_Load(object sender, EventArgs e)
{
LinkButton dynamicButton = new LinkButton();
dynamicButton.ID = "linkDynamic123";
// this id needs to be the same as it was when you
// first sent the page containing the dynamic link to the client
dynamicButton.Click += DynamicButton_Click;
dynamicButton.Visible = false;
Controls.Add(dynamicButton);
}
public void DynamicButton_Click(object sender, EventArgs e)
{
// as you created the control during Page.Load, this event will be fired.
((LinkButton)sender).Visible = true;
}
I have an aspx page which holds 2 user controls
UC1: Edit page - this has the fields for editing or data entry.
UC2: Notification page - this has a simple message box with jquery function
in my aspx i have this function:
public void ShowMessage(string status, string message)
{
Notification1.Message = message; //this is my user control UC2
Notification1.Status = status;
Notification1.DataBind();
}
now when my aspx page needs to show a message this works fine, but when i want the user control 1 to show a message like (invalid field, or wrong amount) it doesn't do anything. Now it gets called but jquery just doesn't react to it.
in UC2 -notification user control this is what I have:
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.js"></script>
<script type="text/javascript">
function showMsg(classname) {
$("#MsgBox").attr('class', classname);
$("#MsgBox").show().delay(5000).fadeOut();
}
</script>
<div id="MsgBox" class="info"><asp:Label ID="lblMessage" runat="server" /></div>
codebehind
public string Status{ get; set; }
public string Message { get; set; }
public override void DataBind()
{
if (Message != string.Empty)
{
lblMessage.Text = Message;
Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "showMsg('" + Status + "');", true);
}
}
and this is how i call the function from user control to aspx page:
((myaspxpage)this.Page).ShowMessage("error", "This is my error message.");
any help will be much appreciated! and if further details is needed just let me know.. Thanks in advance.
**EDIT: I tried putting the jquery and message box inside my Edit page to see if it would work that way and it doesn't So it seems that jquery is not working well within a usercontrol??
Move your codes of DataBind() method into OnPreRender. This should work. The reason is that you don't know which code from which step of your page cycle (init, load, bind, ...) is going to change the Message property.
Like in your case it seems you have a button click event where you are setting the Message property from. This is too late because your Notification1 control is already databound.
Leaving it as the latest stage makes it work:
protected override void OnPreRender()
{
if (Message != string.Empty)
{
lblMessage.Text = Message;
Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "showMsg('" + Status + "');", true);
}
}
I found the error is what that my button that was calling the function in aspx page was inside an update panel and i needed to add a trigger event to make it work.. Thanks everybody for the help it was that update panel causing the error :(
I have a class that defines a Hierarchical RadGrid that I will be using application wide. This grid has many column so this is the best implementation for me, as I will be overriding specific characteristics of the grid based om implementation.
The grid will function in a different manner based on the access level of the user. On a 'basic user level' they will have a Add New Item/Edit Item on the parent grid and Edit, Reject(delete), Approve(Update) on the Child Grid
The next level will be a 'Approver' role. They will NOT have Add New Item/Edit Item on the parent grid and will only have Reject(Edit) on the child. The edit action that the user will take in this role when rejecting an item is that they will be required to enter a comment through a user control that will be launched when the click the reject button. The problem that I am having is that the custom user control is not displaying for a DetailTableView.EditFormSettings when using a GridButtonColumn as the firing event. Any thoughts? TIA
private void SubmittedBatchesRadGrid_ItemDataBound(object sender, GridItemEventArgs e)
{
GridDataItem _dataItem = e.Item as GridDataItem;
if (_dataItem == null) return;
if (e.Item.OwnerTableView.Name == "SubmittedBatchesRadGrid_ChildGrid")
{
SetChildGridCommandColumns(sender, e);
return;
}
if (_dataItem.KeyValues == "{}") { return; }
SetMasterGridCommandColumns(sender, e, _dataItem);
}
private static void SetChildGridCommandColumns(object sender, GridItemEventArgs e)
{
const string _jqueryCode = "if(!$find('{0}').confirm('{1}', event, '{2}'))return false;";
const string _confirmText = "<p>Rejecting this adjustment will mean that you will have to also reject the batch when you are done processing these items.</p><p>Are you sure you want to reject this adjustment?</p>";
((ImageButton)(((GridEditableItem)e.Item)["PolicyEditRecord"].Controls[0])).ImageUrl = "/controls/styles/images/editpencil.png";
ImageButton _btnReject = (ImageButton)((GridDataItem)e.Item)["DeleteTransaction"].Controls[0];
_btnReject.CommandName = "Update";
_btnReject.ImageUrl = "/controls/styles/images/decline.png";
_btnReject.ToolTip = "Reject this item";
//_btnReject.Attributes["onclick"] = string.Format(_jqueryCode, ((Control)sender).ClientID, _confirmText, "Reject Adjustment");
}
private void SubmittedBatchesRadGrid_DetailTableDataBind(object sender, GridDetailTableDataBindEventArgs e)
{
e.DetailTableView.EditFormSettings.EditFormType = GridEditFormType.WebUserControl;
e.DetailTableView.EditFormSettings.UserControlName = "/Controls/RejectedAdjustmentComment.ascx";
e.DetailTableView.EditMode = GridEditMode.PopUp;
e.DetailTableView.CommandItemSettings.ShowAddNewRecordButton = false;
GridDataItem _dataItem = e.DetailTableView.ParentItem;
e.DetailTableView.DataSource = AdjustmentAPI.GetAdjustmentsByBatch(Convert.ToInt32(_dataItem.GetDataKeyValue("BatchID").ToString()), PolicyClaimManualAdjustmentCode);
}
It looks like you just need to use OnClientClick instead, and return the value of the confirm dialog.
_btnReject.OnClientClick = "return confirm(\"Are you sure you?\");"
RadAjax has a little quirk when it comes to confirm dialogs, so you may need to use this instead:
_btnReject.OnClientClick = "if (!confirm(\"Are you sure?\")) return false;"
So I thought I would share my solution in case anyone else needs it.
I was barking up the wrong tree with the edit control. Even though a comment is part of the dataset in the RadGrid I don't want to edit the existing record. I decided to create a usercontrol to handle the process. The RadWindow does not take .ascx pages directly so I started with a .aspx wrapper page and inserted the control there. Then I changed the OnClientClick event to launch the RadWindow loading the new aspx file passing the parameters I needed to the usercontrol. The usercontrol saves the comment to the database and updates the record status and then closes.
I modified this section from above:
private static void SetChildGridCommandColumns(object sender, GridItemEventArgs e)
{
((ImageButton)(((GridEditableItem)e.Item)["PolicyEditRecord"].Controls[0])).ImageUrl = "/controls/styles/images/editpencil.png";
ImageButton _btnReject = (ImageButton)((GridDataItem)e.Item)["DeleteTransaction"].Controls[0];
int _manualAdjustmentId = Convert.ToInt32(((GridDataItem)e.Item)["ManualAdjustmentId"].Text);
int _manualAdjustmentBatchId = Convert.ToInt32(((GridDataItem)e.Item)["ManualAdjustmentBatchId"].Text);
_btnReject.ImageUrl = "/controls/styles/images/decline.png";
_btnReject.ToolTip = "Reject this item";
_btnReject.OnClientClick = String.Format("OpenRadWindow('/controls/RejectedAdjustmentComment.aspx?manualAdjustmentId={0}&manualAdjustmentBatchId={1}', 'CommentDialog');return false;", _manualAdjustmentId, _manualAdjustmentBatchId);
}
private void SubmittedBatchesRadGrid_DetailTableDataBind(object sender, GridDetailTableDataBindEventArgs e)
{
//I deleted this section
e.DetailTableView.EditFormSettings.EditFormType = GridEditFormType.WebUserControl;
e.DetailTableView.EditFormSettings.UserControlName = "/Controls/RejectedAdjustmentComment.ascx";
e.DetailTableView.EditMode = GridEditMode.PopUp;
//
e.DetailTableView.CommandItemSettings.ShowAddNewRecordButton = false;
GridDataItem _dataItem = e.DetailTableView.ParentItem;
e.DetailTableView.DataSource = AdjustmentAPI.GetAdjustmentsByBatch(Convert.ToInt32(_dataItem.GetDataKeyValue("BatchID").ToString()), PolicyClaimManualAdjustmentCode);
}
I added this to the page with the datagrid:
<telerik:RadWindowManager ID="SubmittedBatchesWindow" runat="server">
<windows>
<telerik:RadWindow ID="CommentDialog" runat="server" Title="Rejected Agjustment Comment Dialog"
Height="350px" Width="440" Left="250px" ReloadOnShow="false" ShowContentDuringLoad="false"
Modal="true" VisibleStatusbar="false" />
</windows>
</telerik:RadWindowManager>
I created a new aspx file and inserted the new ascx control inside
<form id="form1" runat="server">
<telerik:RadScriptManager ID="RadScriptManager1" runat="server">
</telerik:RadScriptManager>
<uc:RejectedComment id="RejectionComment1" runat="server" />
</form>
I added my code behind for the update in the ascx file, the javascript for the front end
<script language ="javascript" type ="text/javascript" >
//<![CDATA[
function GetRadWindow() {
var oWindow = null;
if (window.radWindow) oWindow = window.radWindow; //Will work in Moz in all cases, including clasic dialog
else if (window.frameElement.radWindow) oWindow = window.frameElement.radWindow; //IE (and Moz as well)
return oWindow;
}
function CancelEdit() {
GetRadWindow().close();
}
//]]>
</script>
and last but not least closing the window after a successful update in the button click event;
Page.ClientScript.RegisterStartupScript(Page.GetType(), "", "CancelEdit();", true);
I hope someone else finds this useful. It took me several hours hunting the telerik site to find this piece by piece.
I have an aspx master/content page scenario. The parent page has an IFrame which points to a child.aspx. The child.aspx has a checkbox, On page_load of child.aspx, I want to show/hide the checkbox depending on the following logic:
- if the child.aspx is opened directly, then I have to show the checkbox.
- if the child.aspx is opened in the IFrame, then I have to hide the checkbox.
Basically, I want to check in child.aspx, if it contains a parent window then hide the checkbox control otherwise show it.
I will prefer the show/hide code in codebehind in Page_load event as I have to execute some more logic depending on whether the it is opened from parent window or not.
Till now I did the following:
In child.aspx
<asp:Content ID="Content1" ContentPlaceHolderID="Main" Runat="Server">
<script language="javascript" type="text/javascript">
function DoesParentExists()
{
var bool = (parent.location == window.location)? false : true;
var HClientID ='<%=hfDoesParentExist.ClientID%>';
document.getElementById(HClientID).Value = bool;
}
</script>
<div>
<h2>Content - In IFrame</h2>
<asp:HiddenField runat="server" id="hfDoesParentExist" />
<asp:CheckBox ID="chkValid" runat="server" />
<asp:ImageButton ID="ImageButton_FillW8Online" ImageUrl="~/images/expand.gif"
OnClick="btnVerify_Click" runat="server" style="height: 11px" />
</div>
</asp:Content>
in client.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "DoesParentExists", "DoesParentExists()", true);
if (hfDoesParentExist.Value == "true")
{
chkValid.Visible = false;
}
}
Using RegisterClientScriptBlock, I get error in JS. That the object hfDoesParentExist doesn't exist 'coz the control is not yet created. Right? I tried using RegisterStartupScript but in codebehind I always get null in hidden variable. I don't want to use the on button click or something like it. I need it on page_load event only. How to resolve the issue?
This line:
document.getElementById(HClientID).Value = bool;
Should be: (lower case value)
document.getElementById(HClientID).value = bool;
Also you cannot check the value of a hidden field set by javascript register callback, in the current executing context on the server side.
I would move the logic to the client side to hide or show the checkbox. If the field must indeed be removed from the page you can do that as well with javascript.
function DoesParentExists()
{
var bool = (parent.location == window.location)? false : true;
var cehckboxId ='<%=chkValid.ClientID%>';
if(bool){
document.getElementById(cehckboxId).style.display = 'none';
}
else {
document.getElementById(cehckboxId).style.display = 'block';
}
}
You may want to wrap the checkbox with a div and hide the container also to include the label.
To do it server-side, I would rely on a querystring parameter. Have the parent page load the child page by appending ?inframe=1. Then check for that value in your Page_Load.
I am having what I believe should be a fairly simple problem, but for the life of me I cannot see my problem. The problem is related to ScriptManager.RegisterStartupScript, something I have used many times before.
The scenario I have is that I have a custom web control that has been inserted into a page. The control (and one or two others) are nested inside an UpdatePanel. They are inserted onto the page onto a PlaceHolder:
<asp:UpdatePanel ID="pnlAjax" runat="server">
<ContentTemplate>
<asp:PlaceHolder ID="placeholder" runat="server">
</asp:PlaceHolder>
...
protected override void OnInit(EventArgs e){
placeholder.Controls.Add(Factory.CreateControl());
base.OnInit(e);
}
This is the only update panel on the page.
The control requires some initial javascript be run for it to work correctly. The control calls:
ScriptManager.RegisterStartupScript(this, GetType(),
Guid.NewGuid().ToString(), script, true);
and I have also tried:
ScriptManager.RegisterStartupScript(Page, Page.GetType(),
Guid.NewGuid().ToString(), script, true);
The problem is that the script runs correctly when the page is first displayed, but does not re-run after a partial postback. I have tried the following:
Calling RegisterStartupScript from CreateChildControls
Calling RegisterStartupScript from OnLoad / OnPreRender
Using different combinations of parameters for the first two parameters (in the example above the Control is Page and Type is GetType(), but I have tried using the control itself, etc).
I have tried using persistent and new ids (not that I believe this should have a major impact either way).
I have used a few breakpoints and so have verified that the Register line is being called correctly.
The only thing I have not tried is using the UpdatePanel itself as the Control and Type, as I do not believe the control should be aware of the update panel (and in any case there does not seem to be a good way of getting the update panel?).
Can anyone see what I might be doing wrong in the above?
Thanks :)
Well, to answer the query above - it does appear as if the placeholder somehow messes up the ScriptManager.RegisterStartupScript.
When I pull the control out of the placeholder and code it directly onto the page the Register script works correctly (I am also using the control itself as a parameter).
ScriptManager.RegisterStartupScript(this, GetType(), Guid.NewGuid().ToString(), script, true);
Can anyone throw any light on why an injected control onto a PlaceHolder would prevent the ScriptManager from correctly registering the script? I am guessing this might have something to do with the lifecycle of dynamic controls, but would appreciate (for my own knowledge) if there is a correct process for the above.
I had an issue using this in a user control (in a page this worked fine); the Button1 is inside an updatepanel, and the scriptmanager is on the usercontrol.
protected void Button1_Click(object sender, EventArgs e)
{
string scriptstring = "alert('Welcome');";
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertscript", scriptstring, true);
}
Now it seems you have to be careful with the first two arguments, they need to reference your page, not your control
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "alertscript", scriptstring, true);
I think you should indeed be using the Control overload of the RegisterStartupScript.
I've tried the following code in a server control:
[ToolboxData("<{0}:AlertControl runat=server></{0}:AlertControl>")]
public class AlertControl : Control{
protected override void OnInit(EventArgs e){
base.OnInit(e);
string script = "alert(\"Hello!\");";
ScriptManager.RegisterStartupScript(this, GetType(),
"ServerControlScript", script, true);
}
}
Then in my page I have:
protected override void OnInit(EventArgs e){
base.OnInit(e);
Placeholder1.Controls.Add(new AlertControl());
}
Where Placeholder1 is a placeholder in an update panel. The placeholder has a couple of other controls on in it, including buttons.
This behaved exactly as you would expect, I got an alert saying "Hello" every time I loaded the page or caused the update panel to update.
The other thing you could look at is to hook into some of the page lifecycle events that are fired during an update panel request:
Sys.WebForms.PageRequestManager.getInstance()
.add_endRequest(EndRequestHandler);
The PageRequestManager endRequestHandler event fires every time an update panel completes its update - this would allow you to call a method to set up your control.
My only other questions are:
What is your script actually doing?
Presumably you can see the script in the HTML at the bottom of the page (just before the closing </form> tag)?
Have you tried putting a few "alert("Here");" calls in your startup script to see if it's being called correctly?
Have you tried Firefox and Firebug - is that reporting any script errors?
When you call ScriptManager.RegisterStartupScript, the "Control" parameter must be a control that is within an UpdatePanel that will be updated. You need to change it to:
ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), script, true);
The solution is to put the scripts in an outside js file (lets called 'yourDynamic.js') and re-register de file everytime you refresh the updatepanel.
I use this in the updatepanel_prerender event:
ScriptManager.RegisterClientScriptBlock(UpdatePanel1, UpdatePanel1.GetType(), "UpdatePanel1_PreRender", _
"<script type='text/javascript' id='UpdatePanel1_PreRender'>" & _
"include('yourDynamic.js');" & _
"removeDuplicatedScript('UpdatePanel1_PreRender');</script>" _
, False)
In the page or in some other include you will need this javascript:
// Include a javascript file inside another one.
function include(filename)
{
var head = document.getElementsByTagName('head')[0];
var scripts = document.getElementsByTagName('script');
for(var x=0;x<scripts.length;> {
if (scripts[x].getAttribute('src'))
{
if(scripts[x].getAttribute('src').indexOf(filename) != -1)
{
head.removeChild(scripts[x]);
break;
}
}
}
script = document.createElement('script');
script.src = filename;
script.type = 'text/javascript';
head.appendChild(script)
}
// Removes duplicated scripts.
function removeDuplicatedScript(id)
{
var count = 0;
var head = document.getElementsByTagName('head')[0];
var scripts = document.getElementsByTagName('script');
var firstScript;
for(var x=0;x<scripts.length;> {
if (scripts[x].getAttribute('id'))
{
if(scripts[x].getAttribute('id').indexOf(id) != -1)
{
if (count == 0)
{
firstScript = scripts[x];
count++;
}
else
{
head.removeChild(firstScript);
firstScript = scripts[x];
count = 1;
}
}
}
}
clearAjaxNetJunk();
}
// Evoids the update panel auto generated scripts to grow to inifity. X-(
function clearAjaxNetJunk()
{
var knowJunk = 'Sys.Application.add_init(function() {';
var count = 0;
var head = document.getElementsByTagName('head')[0];
var scripts = document.getElementsByTagName('script');
var firstScript;
for(var x=0;x<scripts.length;> {
if (scripts[x].textContent)
{
if(scripts[x].textContent.indexOf(knowJunk) != -1)
{
if (count == 0)
{
firstScript = scripts[x];
count++;
}
else
{
head.removeChild(firstScript);
firstScript = scripts[x];
count = 1;
}
}
}
}
}
Pretty cool, ah...jejeje
This part of what i posted some time ago here.
Hope this help... :)
I had an issue with Page.ClientScript.RegisterStartUpScript - I wasn't using an update panel, but the control was cached. This meant that I had to insert the script into a Literal (or could use a PlaceHolder) so when rendered from the cache the script is included.
A similar solution might work for you.
DO NOT Use GUID For Key
ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UpdatePanel)
Guid.NewGuid().ToString(), myScript, true);
and if you want to do that , call Something Like this function
public static string GetGuidClear(string x)
{
return x.Replace("-", "").Replace("0", "").Replace("1", "")
.Replace("2", "").Replace("3", "").Replace("4", "")
.Replace("5", "").Replace("6", "").Replace("7", "")
.Replace("8", "").Replace("9", "");
}
What worked for me, is registering it on the Page while specifying the type as that of the UpdatePanel, like so:
ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UpdatePanel) Guid.NewGuid().ToString(), myScript, true);
Sometimes it doesnt fire when the script has some syntax error, make sure the script and javascript syntax is correct.
ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(),script, true );
The "true" param value at the end of the ScriptManager.RegisterStartupScript will add a JavaScript tag inside your page:
<script language='javascript' defer='defer'>your script</script >
If the value will be "false" it will inject only the script witout the --script-- tag.
I try many things and finally found that the last parameter must be false and you must add <SCRIPT> tag to the java script :
string script = "< SCRIPT >alert('hello!');< /SCRIPT>";
ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), key, script, **false**);