Showing posts with label page. Show all posts
Showing posts with label page. Show all posts

Wednesday, March 28, 2012

dynamic html production to call ajax post via javascript

I am maintaining a page that creates html (not server controls) elements dynamically and when one changes I need to call the ajax postback. Is that possible? The page that is created can't know ahead of time that it will need to post through ajax....

So long as you add a client-side Event handler to your html control when you create it, yes, you can wire it up to make asynchronous requests:http://www.mikesdotnetting.com/Article.aspx?ArticleID=40. Note, the methodology outlined in the article doesn't make an ASP.NET Ajax request or postback. It differs in that it only makes a call to the server-side method you want to invoke. This can be better than using ASP.NET Ajax, in that you aren't recreating all the controls on the page.

Dynamic highlight should be easy! (UpdatePanelAnimationExtender)

Hi,

I have a page fragment which looks roughly like:


<UpdatePanel>
<Repeater>
<Item>
<div id="something-#">item text</div>
</Item>
</Repeater>
</UpdatePanel>


When a new item is added, I want to have the newly added <div> higlight. So far I've manged to get the first item to highlight with an UpdatePanelAnimationExtender:

<ajaxToolkit:UpdatePanelAnimationExtender ID="upae" BehaviorID="Highlight"
runat="server" TargetControlID="UpdatePanel1">
<Animations>
<OnUpdated>
<Sequence>
<Color AnimationTarget="something-1"
Duration=".5" PropertyKey="backgroundColor"
StartValue="#FFFF90" EndValue="#FFFFFF" />
</Sequence>
</OnUpdated>
</Animations>
</ajaxToolkit:UpdatePanelAnimationExtender>

What I can't figure out how to do is get the most recently added item to highlight. It seems like I need to be able to set the "AnimationTarget=" attribute in server code, but after reading posts on here I believe I can't.

Is there any easy way to do this?

Well, to reply to myself, here's how I achieved it. (I'm sure there must be an easier way though).

In my button click event handler I add a data item with the Id of the new object.

if (ScriptManager.IsInAsyncPostBack)
{
System.Web.Script.Serialization.JavaScriptSerializer json =
new System.Web.Script.Serialization.JavaScriptSerializer();

// Return the new CommentId ScriptManager.RegisterDataItem(CommentsUpdatePanel, json.Serialize(comment.CommentId),true);
}

Then in my page, use the EndRequestHandler to pick up the new Id. I then dynamically create some animation code
using the client ID that I've just created.

 function EndRequestHandler(sender, args)
{
var dataItems = args.get_dataItems();
var newCommentId;

if (dataItems[CommentsUpdatePanel] != null)
{
newCommentId = dataItems[CommentsUpdatePanel];
}

 var colorAni = new AjaxControlToolkit.Animation.ColorAnimation(newCommentEl,
2, 30, "style", "backgroundColor", "#FFEF3F", "#FFFFFF");
/// More animation code }
It works, but it seems very clunky to me. 

Hi,

There are a couple of ways you could do this that are a little easier. A better approach would be something like <Color TargetScript="GetLatestDiv()" ... > combined with function GetLatestDiv that does a look up on the ID stored in your data item and returns its element.

Thanks,
Ted

Ted,Thanks for your reply.

I did consider this method, but the problem I faced is getting to the dataItem in the 'GetLatestDiv()' method. The documentation says that:

"If you use the RegisterDataItem method of the ScriptManagercontrol to send extra data during an asynchronous postback, you canaccess that data from the PageLoadingEventArgs, PageLoadedEventArgs,and EndRequestEventArgs objects"

In other words, as far as I can tell, I need to be in the EndRequestHandler method to get at the dataItem. It appears that EndRequestHandler() is called after GetLatestDiv() is evaluated, so I can't even use a shared variable, which would be quite nasty anyway.

Is there any other way I can get at the DataItem?

Hi,

Right - you'll still need your handler to pull the DataItem out. I was thinking you could then store that in a global var that's later read by GetLatestDiv(). Better yet though, you could make it one step simpler and just say TargetScript="_lastDiv" where _lastDiv is a global reference to the element you obtained from your handler.

Thanks,
Ted

Dynamic generated Controls doesnt work, javascript error

I have an ajax enabled control which has a Dropdownlist that changes the Textbox when index gets changed. It is working fine if I use an ASPX page that contains the control in design time.

However, when I dynamically add this control to the ASPX in run time, I got an error when the Dropdownlist is triggered:

Javascript error: System.InvalidOperationException: A control with ID 'myDropDownList' could not be found for the trigger in UpdatePanel..etc..

What should I do? Please help..

There's a good chance that if you look at your page source you'll find that the dynamic control does not have a clientside Id of 'myDropDownList'. It'll probably have something more complex like ct100_myDropDownList or something.

Two possible fixes: 1) wire up your javascript on something other than the id (e.g. iterate over getElementsByTagName), or 2) render the control's ClientID inside a script tag on the page like: var ddl = '<%= myDropDownList.ClientID %>'

HOpe that helps.

Dynamic created ModalPopup Window

Hi,

I am having a lot of modal popup windows on my page (20+).

When i click various buttons on my page, various modal popupwindows should apear. But I don't want to define all the windows in the aspx, because the windows are pretty large.

So I think it would be fine to place one Panel containing an UpdatePanel and one ModalPopupExtender on the page and on clicking a button on the page i create an composite control and place it inside the Updatepanel, update() and show the modal dialog from code behind. This works fine if the content of the modal popup doesn't contain any buttons. But when i use buttons inside the popup window, their events doesn't fire at all.

Here is some code:

The ASPX:

 <asp:panel id="pnlPopUp" runat="server" style="display: none">
<div style="background-color: LightGrey">
<asp:panel id="header" runat="server">
<asp:label id="lblHeader" runat="server" />
<asp:linkbutton id="lbClose" runat="server" text="X" onclientclick="$find('mpePopUp').hide(); return false;" />
</asp:panel>
<asp:updatepanel runat="server" id="updPopup" childrenastriggers="true" updatemode="conditional">
<contenttemplate>
<asp:panel id="pnlBody" runat="server" cssclass="body" />
</contenttemplate>
</asp:updatepanel>
</div>
</asp:panel>
<cc1:modalpopupextender id="mpePopUp" behaviorid="mpePopUp" popupcontrolid="pnlPopUp" runat="server" dropshadow="true"repositionmode="RepositionOnWindowResizeAndScroll" targetcontrolid="dummy" backgroundcssclass="modalBackground" />

CODE:

public partialclass _Default : System.Web.UI.Page
{
public MDMWindow2 w2 =null;

protected override void OnInit( EventArgs e )
{
base.OnInit( e );
w2 =new MDMWindow2( );
w2.Bubble +=new EventHandler( w2_Bubble );
}

void w2_Bubble(object sender, EventArgs e)
{
int x = 0;// This Point get NEVER hit}protected void ShowWindow2(object sender, EventArgs e )
{
w2.HeaderText ="WWW2";
updPopup.ContentTemplateContainer.Controls.Add( w2 );
updPopup.Update( );
mpePopUp.Show( );
}

and the code of the control:

using System;
using System.Web.UI;
using System.Web.UI.WebControls;

/// <summary>
/// Summary description for PopUpPanel
/// </summary>public class MDMWindow2 : CompositeControl
{
private Label headerLabel;
private Button button;

public String HeaderText
{
get{EnsureChildControls( );return headerLabel.Text;
}
set{EnsureChildControls( );headerLabel.Text =value;
}
}

public MDMWindow2( )
{
}

public event EventHandler Bubble;

protected override void OnLoad( EventArgs e )
{
base.OnLoad( e );
EnsureChildControls( );
}

protected override void CreateChildControls( )
{
EnsureChildControls( );
headerLabel =new Label( );
headerLabel.ForeColor = System.Drawing.Color.Red;
this.Controls.Add( headerLabel );

button =new Button( );
button.CommandName ="Click";
button.Text ="ClickMe";
Controls.Add( button );
button.Click +=new EventHandler( b_Click );

}

void b_Click(object sender, EventArgs e )
{
Bubble(this, e );// This Point get NEVER hit
}
}

Can anybody help? What is wrong with wiring the eventHandlers? Is the updatepanel the probl?em? Or can anybody show me an better way to create modal popups at serverside?

Thnx

I did something like this using user controls (.ascx files). The .aspx file has an UpdatePanel whose content is an asp:Panel with an asp:PlaceHolder in it and an asp:Button. The button is configured with an OnCommand handler and an initial CommandName of 'Inactive'. A LinkButton on the page triggers a partial postback which does 3 main things: a) does a LoadControl of a .ascx file into the Placeholder; b) changes the CommandName of the Button to "EntryForm" (or something logically associated with the .ascx); c) calls Show() on the modal popup.

After the partial rendering completes, the modal popup is shown. When the Button is pressed, the OnCommand is run, and it uses the CommandName to do the right thing for the particular .ascx that was loaded. It's important that in Page_Load, if it's a postback, that the loaded .ascx is re-loaded (using LoadControl) so that the viewstate is restored and the controls on the .ascx can get updated with the values entered on the modalpopup form. During OnCommand, if a different .ascx needs to be shown, it unloads the Placeholder's controls and uses LoadControl for the next .ascx. If the sequence is done, it sets the CommandName back to "Inactive" and hides the modalpopup.

Hope that helps,

Donnie

This sounds good. But in my Dialogs I will have more various controls like dropdownllist or textboxes wich will have to be bound to an eventhandler too. They have to be in the controls.

It would be perfect, if I can handle the events, which are triggered by my control, inside the page.



Sounds like, then, after you use LoadControl, the page just needs to add event handlers in its code-behind to the controls in the .ascx that was dynamically loaded.

Dynamic create UpdatePanel during postback

Hi,

I want to add a UpdatePanel into page dynamically during postback, see bellow code for detail. The problem is although UpdatePanel control was successful created, I cannot get its reference in later postback times.

// dummy template
publicclassMyTemplate :ITemplate
{
publicvoid InstantiateIn(Control container)

{

}

}

// create UpdatePanel during postback
protectedvoid Button5_Click(object sender,EventArgs e)
{

Microsoft.Web.UI.UpdatePanel u =new Microsoft.Web.UI.UpdatePanel();

u.ID ="udpDynamic";

u.ContentTemplate =newMyTemplate();

u.Mode = Microsoft.Web.UI.UpdatePanelMode.Conditional;

Microsoft.Web.UI.ControlEventTrigger trigger =new Microsoft.Web.UI.ControlEventTrigger();

trigger.ControlID ="Button6";// this button is created in design time

trigger.EventName =

"Click";

u.Triggers.Add(trigger);

this.Form.Controls.Add(u);

}

// other postback event
protectedvoid Button6_Click(object sender,EventArgs e)
{

Label test =newLabel();

test.Text ="I'm new portlet " +DateTime.Now.ToLongTimeString();

Microsoft.Web.UI.UpdatePanel u = (Microsoft.Web.UI.UpdatePanel)this.Form.FindControl("udpDynamic");

u.Controls.Add(test);// error! u is null

}

// here is HTML code generated, as I can see the UpdatePanel control was created successfully
<div id="udpDynamic"></div>

<components>
<pageRequestManager id="_PageRequestManager" updatePanelIDs="UpdatePanel1,UpdatePanel2,UpdatePanel3,udpDynamic" asyncPostbackControlIDs="Button4,Button6" scriptManagerID="ScriptManager1" form="form1" />
</components>

Well, I can't solve your problem, but I can tell you one thing that is wrong with your code:

When adding a control to an UpdatePanel, you need to use the ContentTemplateContainer.Controls.Add(...) property of the UpdatePanel, otherwise you will not see the control (in a book I read, it will actually throw an error, but I guess it isn't for you).

I work in VB.NET, although I can usually understand C#, but when I try to convert from System.Web.UI.Control (which is what FindControl returns) to System.Web.UI.UpdatePanel, I receive the following error message:

Unable to cast object of type 'System.Web.UI.Control' to type 'System.Web.UI.UpdatePanel'.

I am surprised that you are not receiving this error as well, if you take a look at my posting athttp://forums.asp.net/t/1154222.aspx you can see more details about this problem I am having. Good Luck!

Dynamic Control creation not persisting through PostBack

Hey guys,

I've done some searching on dynamic control creation in the forums, but none of them take me to an Atlas page. I'm trying to build a HR Notification form with some simple Atlas UpdatePanels. Basically, I want to dynamically add Labels and TextBoxes to this form. For instance, if you select 3 from the Number of Children DDL, I want 3 child forms to be created under it. I've been able to create the forms (at least theoretically, I just create "test" Labels right now). The problem I'm running into is being able to read from these dynamically created Controls.

When I submit the form as a regular PostBack, all of my created labels seem to be lost. I get null exceptions when I try to use FindControl. Here are some code snippets:

protected void ddlNumChildren_SelectedIndexChanged(object sender, EventArgs e) {int runNum = Convert.ToInt32(ddlNumChildren.SelectedValue.ToString());int count = 0;while (count < runNum) { Label text=new Label(); text.ID ="testLabel" + count; text.Text ="test"; phNumChildren.Controls.Add(text); count++; } }protected void btnSubmit_Click(object sender, EventArgs e) {int runNum = Convert.ToInt32(ddlNumChildren.SelectedValue.ToString());int count = 0;while (count < runNum) { Label lbltest = phNumChildren.FindControl("testLabel" + count)as Label; Response.Write(lbltest.Text); } }

I'm assuming I have to save this data before the postback, but I need a little help in how I can do this. Thanks for your time and any help you can provide.

The problem is that the controls do not exist when the page is recreated during postback. You have two options :
1) Recreate the page during the Init() event if you have atlas UpdatePanels or Page_Load() if not
2) try http://www.denisbauer.com/ASPNETControls.aspx
3) Write your own code to save all controls in ViewState and reload them during the Init() event

Dynamic content paired with a popupControlextender

Hi folks,

I have implemented a popup control exteder which works great, however I have to populate the content of the popup at page load. I would like the content of the popup to be dynamically generated at the time the popup is called with a server callback, kind of a PopupControlExtender meets DynamicPopulateExtender. I guess what i'm looking for is just an indication of the complexity of this task, and perhaps a pointer in the right direction.

Cheers,

Howard

Hi,

Actually, PopupControl has this functionality built in... you can set the DynamicServicePath, DynamicServiceMethod, DynamicContextKey, and DynamicControlID properties of PopupControlExtender and it will fetch dynamic content before it's shown.

Thanks,
Ted

Dynamic CollapsiblePanel

I am surely a novice, but was wondering if it is possible to dynamically build a page of collapsible panels based on the values in a SQL table. The code size would be greatly reduced if it can be done.Just another forum that noone uses!

I'll be honest, this is a very vague question. And it seems as though you are fishing for free code. We aren't here to code projects for you. If you are looking for pointers, I'll gladly provide this.

The approach I would take is to use either a SqlDataSource or ObjectDataSource to retrieve the data. I like working with objects, so it tends to take more code up front to get the data from SQL and turn it into objects in my object model. But once done, I then use the ObjectDataSource to get the data ready for binding.

Then you can use any number of databound controls. One example might be the Repeater control. This is a very free form control that will let you provide any HTML per object (or row) returned from the datasource. In the ItemTemplate, you just define the CollapsiblePanelExtender as you would in any databound control.

If you get stuck, please post here with the code that is blocking you and I'll do what I can to help.


Got it working. The problem was with the page sub-class.

dynamic cascaded drop down

Hi..

well in my web page based on a parameter user selects i need to create contents dynamically

for eg if A is passed than page will have only 1 drop down but if B is passed it might have 7 8 drop downs in it..

this is one part of the problem..once i am able to create them i need to address there selection index change even which will call again some fucntion

which will reload all othr drop dwon whch were created dynamically

so its kind of generating cascaded drop down dynamically and the parent control id could be more than one

Can some one help me out

in case any one is here wondering what happened to the problem

the solution is same as

http://forums.asp.net/t/1090354.aspx

Dynamic Atlas page

I am making a completely dynamic web page. I want to use Atlas for UI handling.
This means that all atlas controls I create in codebehind (But sometimes a template would be useful, but only html template - atlas code should be generated dynamically). The main idea is that while you enter data, page updates itself and either edits data or changes whole behaviour. So I have some questions
1) Where can I see which classes create which elements in Script tag?
2) Is it possible at all to dynamically change behaviour - for example, to make the same html button call different actions or to completely change part of html (span element) and accordingly change atlas scripts?
3) how to dynamically add atlas controls from codebehind and avoid rendering visible control - make only atlas script?
4) how to make visible part of atlas control to appear somewhere else not after closing HTML tag?It shouldn't work that way, I think. Atlas is more client side then server framework..point is to make smart client webapplications which requests only actually needed data from server. You can create all controls from code, but on client side it will look same as if you create them much easier way in designer.
It's all my personal option

You didn't understand the problem - I want to put more action in client-side. For example, when filling out order form, I want to check data (and autofill some fields) without postback.
But the way I want to build UI is dynamic - I make product definition (what data are necessary for particular product) and screen definition (where these necessary data show up in UI). And then I have helper class that goes through those definitions and creates UI controls. Currently I can create native ASP.NET controls, but I would like to use ATLAS instead.
So the problem is that all examples of ATLAS scripts I have seen so far are statically typed in *.aspx page. But I want to create those scripts at runtime using Microsoft.Web.UI.* classes. But I cannot find all classes that correspond to examples in static scripts. For example, how can I programmatically create serviceMethod tag?
Not all client-side Atlas controls have a server-side version yet. Forexample, there is no serviceMethod Atlas server-control yet.
You would have to write them yourself, or wait until a new version ofAtlas is released which includes more server-controls for the Atlasclient-side controls.

Where can I get more info on how to create a class that creates ATLAS script? What should I inherit from, what methods need to be implemented, etc?

Dynamic association between UpdatePanel and UpdateProgress not working

Hi,

I haven't really used the ASP.NET AJAX framework before and I'm trying to get this to work without any luck. On my page is a repeater control and in its itemtemplate I generate an UpdatePanel and an UpdateProgress control (and a couple of other items) along with a LinkButton. The UpdatePanel has another repeater inside it. The idea is when I click on of the LinkButtons, it binds a datasource to the innermost repeater and refreshes the associated UpdatePanel (the panel is set to Conditional updatemode). It all works well but the associated UpdateProgress doesn't show, ever.

I've tried declarative setting the AssociatedUpdatePanelID in my ASP.NET code and I've tried to set it programatically in the ItemDataBound property of the outermost repeater (I've tried setting it to ID, ClientID and UniqueID) with no luck. If I leave the AssociatedUpdatePanelID untouched it sort of work but the problem is that ALL UpdateProgress controlls are displayed when a LinkButton is pressed.

The following experimentation code is the one I've been trying to make it work
 <asp:scriptmanager id="ScriptManager1" runat="server"> </asp:scriptmanager> <asp:repeater id="rptAlternatives" runat="server" onitemcreated="rptAlternatives_ItemCreated" onitemdatabound="rptAlternatives_ItemDataBound"> <itemtemplate> <div style="border: 1px solid #000; width: 300px; height: 100px; margin: 10px 0 10px 0;"> <asp:linkbutton id="lnkToggleSementPanel" runat="server" text="Toggle segments"></asp:linkbutton> <asp:updateprogress id="progress" runat="server" AssociatedUpdatePanelID="updSegmentPanel"> <ProgressTemplate> Loading... </ProgressTemplate> </asp:updateprogress> <asp:updatepanel id="updSegmentPanel" runat="server" updatemode="Conditional"> <contenttemplate> <asp:repeater id="rptSegments" runat="server"> <headertemplate> <div style="background-color: red; width: 100%;"> </headertemplate> <itemtemplate><%# Container.DataItem%> </itemtemplate> <footertemplate> </div> </footertemplate> </asp:repeater> </contenttemplate> </asp:updatepanel> </div> </itemtemplate> </asp:repeater>

using System;
using System.Collections.Generic;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partialclass _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<int> items =new List<int>();
for (int i = 0; i < 5; i++)
items.Add(i);

this.rptAlternatives.DataSource = items;
this.rptAlternatives.DataBind();
}
}
protected void rptAlternatives_ItemCreated(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
{
LinkButton lnkToggleSementPanel = e.Item.FindControl("lnkToggleSementPanel")as LinkButton;
if (lnkToggleSementPanel !=null)
{
lnkToggleSementPanel.Click +=new EventHandler(lnkToggleSementPanel_Click);
lnkToggleSementPanel.CommandArgument = e.Item.ItemIndex.ToString();
this.ScriptManager1.RegisterAsyncPostBackControl(lnkToggleSementPanel);
}
}
}

protected void rptAlternatives_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
{
UpdatePanel updSegmentPanel = e.Item.FindControl("updSegmentPanel")as UpdatePanel;
if (updSegmentPanel !=null)
{
UpdateProgress progress = e.Item.FindControl("progress")as UpdateProgress;
if (progress !=null)
{
progress.DisplayAfter = 0;

// NON OF THESE WORK!
//progress.AssociatedUpdatePanelID = updSegmentPanel.ClientID;
//progress.AssociatedUpdatePanelID = updSegmentPanel.UniqueID;
//progress.AssociatedUpdatePanelID = updSegmentPanel.ID;
}
}
}
}

void lnkToggleSementPanel_Click(object sender, EventArgs e)
{
LinkButton lnkToggleSementPanel = senderas LinkButton;
if (lnkToggleSementPanel !=null)
{
Control parentControl =
lnkToggleSementPanel.Parent;
UpdatePanel updSegmentPanel = parentControl.FindControl("updSegmentPanel")as UpdatePanel;

if (updSegmentPanel !=null)
{
Repeater rptSegments = updSegmentPanel.FindControl("rptSegments")as Repeater;
if( rptSegments !=null )
{
List<int> items =new List<int>();
for (int i = 0; i <= Convert.ToInt32(lnkToggleSementPanel.CommandArgument); i++)
items.Add(i);

rptSegments.DataSource = items;
rptSegments.DataBind();
updSegmentPanel.Update();

// Delay added for debugging
System.Threading.Thread.Sleep(1000);
}
}
}


}
}

Another thing that I've found strange is that if I move the assigning of the AssociatedUpdatePanelID property FROM ItemDataBound TO ItemCreated it all stops working and if you check the generated control ID's they've not been given proper IDs, i.e the NamingContainer stops working

No takers on this one? It appears Im just missing one piece of the puzzle but I can't figure out which oneSad


Hi,

Here is a working sample:

<%@. Page Language="C#" %><%@. Import Namespace="System.Collections.Generic" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><script runat="server"> protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { List<int> items = new List<int>(); for (int i = 0; i < 5; i++) items.Add(i); this.rptAlternatives.DataSource = items; this.rptAlternatives.DataBind(); } } protected void rptAlternatives_ItemCreated(object sender, RepeaterItemEventArgs e) { //if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item) //{ // LinkButton lnkToggleSementPanel = e.Item.FindControl("lnkToggleSementPanel") as LinkButton; // if (lnkToggleSementPanel != null) // { // lnkToggleSementPanel.Click += new EventHandler(lnkToggleSementPanel_Click); // lnkToggleSementPanel.CommandArgument = e.Item.ItemIndex.ToString(); // this.ScriptManager1.RegisterAsyncPostBackControl(lnkToggleSementPanel); // } //} } protected void rptAlternatives_ItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item) { UpdatePanel updSegmentPanel = e.Item.FindControl("updSegmentPanel") as UpdatePanel; if (updSegmentPanel != null) { UpdateProgress progress = e.Item.FindControl("progress") as UpdateProgress; if (progress != null) { progress.DisplayAfter = 0; } } } } protected void rptAlternatives_ItemCommand(object source, RepeaterCommandEventArgs e) { LinkButton lnkToggleSementPanel = e.Item.FindControl("lnkToggleSementPanel") as LinkButton; if (lnkToggleSementPanel != null) { Control parentControl = lnkToggleSementPanel.Parent; UpdatePanel updSegmentPanel = parentControl.FindControl("updSegmentPanel") as UpdatePanel; if (updSegmentPanel != null) { Repeater rptSegments = updSegmentPanel.FindControl("rptSegments") as Repeater; if (rptSegments != null) { List<int> items = new List<int>(); for (int i = 0; i <= e.Item.ItemIndex; i++) items.Add(i); rptSegments.DataSource = items; rptSegments.DataBind(); updSegmentPanel.Update(); // Delay added for debugging System.Threading.Thread.Sleep(2000); } } } }html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server"> <title>Untitled Page</title></head><body> <form id="form1" runat="server"> <div> <asp:scriptmanager id="ScriptManager1" runat="server"> </asp:scriptmanager> <asp:repeater id="rptAlternatives" runat="server" onitemcreated="rptAlternatives_ItemCreated" onitemdatabound="rptAlternatives_ItemDataBound" OnItemCommand="rptAlternatives_ItemCommand"> <itemtemplate> <div style="border: 1px solid #000; width: 300px; height: 100px; margin: 10px 0 10px 0;"> <asp:updatepanel id="updSegmentPanel" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="true"> <contenttemplate> <asp:linkbutton id="lnkToggleSementPanel" runat="server" text="Toggle segments"></asp:linkbutton> <asp:repeater id="rptSegments" runat="server"> <headertemplate> <div style="background-color: red; width: 100%;"> </headertemplate> <itemtemplate><%# Container.DataItem%> </itemtemplate> <footertemplate> </div> </footertemplate> </asp:repeater> </contenttemplate> <Triggers> </Triggers> </asp:updatepanel> <asp:updateprogress id="progress" runat="server" AssociatedUpdatePanelID="updSegmentPanel"> <ProgressTemplate> Loading... </ProgressTemplate> </asp:updateprogress> </div> </itemtemplate> </asp:repeater> </div> </form></body></html>

Please try it and compare with your own code.

dynamic AnimationExtender

I have a list of users in a database and I want to return the list of users to an aspx page with a user icon. I then want to have an ajaxToolkit:AnimationExtender attached to each icon. I have the ajaxToolkit:AnimationExtender working for a single image on a page with all of the script code in the markup. How do I at runtime set a ajaxToolkit:AnimationExtender for each icon.

Thanks

OK,

I have been playing with the toolkit sample code to try and make it OO to some degree. Here is what I have:

3 functions

1 to make the flyout panel,1 to make the onclick open animation and 1 to make the onclick close animation.

I can make the the first to work but I am having trouble with the last one becuase the sample code uses a asp:linkbutton to close the animation. When I try and build it from code/html it is not being converted into a control and the close animation can't find it's targetcontrol id.

here is the flyout panel:

publicstring BuildAnimationPopup(string inPopUpHTML ,outstring flyout,outstring info,outstring btnCloseParent,outstring close)

{

System.Text.StringBuilder sb =new System.Text.StringBuilder();

flyout ="flyout" +DateTime.Now.Millisecond.ToString(); //just to make it unique

info ="info" +DateTime.Now.Millisecond.ToString(); //just to make it unique

btnCloseParent ="btnCloseParent" +DateTime.Now.Millisecond.ToString(); //just to make it unique

close ="btnClose" +DateTime.Now.Millisecond.ToString(); //just to make it unique

//<!-- "Wire frame" div used to transition from the button to the info panel -->

sb.Append("<div id='"+ flyout +"' style='display: none; overflow: hidden; z-index: 2; background-color: #FFFFFF; border: solid 1px #D0D0D0;'></div>");

//<!-- Info panel to be displayed as a flyout when the button is clicked -->

sb.Append("<div id='"+info+"' style='display: none; ; z-index: 2; opacity: 0; filter: progid:DXImageTransform.Microsoft.Alpha(opacity=0); font-size: 12px; border: solid 1px #CCCCCC; background-color: #FFFFFF; padding: 5px;'>");

sb.Append("<div id='"+btnCloseParent+"' style='float: right; opacity: 0; filter: progid:DXImageTransform.Microsoft.Alpha(opacity=0);'>");

//sb.Append("<asp:LinkButton id='"+close +"' runat='server' OnClientClick='return false;' Text='X' ToolTip='Close' Style='background-color: #666666; color: #FFFFFF; text-align: center; font-weight: bold; text-decoration: none; border: outset thin #FFFFFF; padding: 5px;' />");

sb.Append("<a onclick='return false;' runat='server' id='"+close+"' title='Close' style='background-color: #666666; color: #FFFFFF; text-align: center; font-weight: bold; text-decoration: none; border: outset thin #FFFFFF; padding: 5px;'>X</a>");

sb.Append("</div>");

sb.Append("<div>");

sb.Append(inPopUpHTML);

sb.Append("</div>");

sb.Append("</div>");

return sb.ToString();

}

As you can see I have tried it both ways, using an asp:linkbutton and a plain old <a> with the runat=server tag but the Ajax control still can't find it.

Any thoughts?

Dynamic Animation

Hi threr;

I want create an show a dynamic animation(exactly like select tag window in this page) using AJAX Control Toolkit animation control. At frist, I dont know how can I create a dynamic animation. Second, I want to call the animation via an event instead of button click.

Hi nima_montazeri,

Check outthis post on how to dynamically create Animations. You can't cause an animation to be played in an event other than those it supports. There is a workaround you could try though. You can create a dynamic OnLoad animation in your event which will play as soon as your page is reloaded - you just have to be careful to clear it out before the next postback.

Thanks,
Ted

Dynamic AJAX loaded control with updatepanel problem.

Hi,

Hopefully someone can shed some light onto whether this can be done as I am not having much luck so far.

I have a page with an Update panel. On this page I have a button that through an asynchronous postback loads a usercontrol (lets call it A). The usercontrol that is loaded (A) also has an update panel and a button. When the button on the usercontrol (A) is clicked I want it to load another usercontrol (B) through ajax into the updatepanel.

So we have nested usercontrols and updatepanels - the page hosts Usercontrol A which hosts usercontrol B.

Loading the Usercontrol A is working without a problem and I am persisting the loaded control by use of viewstate and reloading the controls in the OnInit event.

However clicking the button on usercontrol A will not load the usercontrol (B). This is because the click event behind the button does not fire.

I would be grateful if anyone has tried this and found a way of making it work.

Thanks

Hi,

Can you post a simple and clear sample here?


Hi, nzwy1p

Since you dynamically add the first(parent) user control, you should add it to the PlaceHolder in the Page_Load event every time instead of adding it just in theButton's Click event. Because when you only add it in theButton's Click event, after post back, theuser controlwill disappear. And itdoesn't land on your breakpoint inButton1_Click inUserControlA.ascx,There is non UserControlA when your postback by clickingButton1 in theUserControlA.

Try this:

Page:

<%@. Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
UpdatePanel1.Update();
}

protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
UserControl uc;
uc = (UserControl)LoadControl("UserControlA.ascx");
PlaceHolder1.Controls.Add(uc);
}
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" />
</Triggers>
</asp:UpdatePanel>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /></div>
</form>
</body>
</html>

UserControlA:

<%@. Control Language="C#" ClassName="UserControlA" %>

<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
UserControl uc;
uc = (UserControl)LoadControl("UserControlB.ascx");
PlaceHolder1.Controls.Add(uc);
}
</script>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" />
</Triggers>
</asp:UpdatePanel>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button in UserContorlB" />

UserControlB:

<%@. Control Language="C#" ClassName="UserControlB" %>

<script runat="server">

</script>

<asp:Label ID="Label1" runat="server" Text="UserContorlB's content"></asp:Label>

For more help, You can see theselink:http://forums.asp.net/t/1108394.aspx

Let me know if you need more info

Monday, March 26, 2012

dynamic addhandler not working in update panel

hi all,

i have designed a page, with a place holder in it, the placeholder is inside a updatepanel, the placeholder gets filled with images at load, and when i click the viewcart button it get filled with the image information with few dynamic buttons, i have added addhandler for those buttons, but they are not firring up. i am pasting my code here if some one can help me plz.

Dim

updateorderlnkbtn AsNew button ' this is done at the genearal section of the page to make it globalAddHandler updateorderlnkbtn.click,AddressOf cancelBtn_click ' at page init

please help me

hi all

i have done some other changes to the code but still the same problem, if any one of you can give me some idea that would be highly appreciated

thanks


hi all

I have done some thing here that my 5 static buttons that are created at runtime are working fine now but the problem is with the dynamic table, i am placing a delete button in the dynamic table now the dynamic table is created at runtime and i want the delete button to remove the row.

the other buttons (5 buttons) code is something like this , i have wrote the code behing the load, the problem is that i can't wrote the dynamic table code behind the load, the dynammic table is created when i click a viewcart button

please help

Dynamic Accordion with Paging

hi there; using asp.net 2.0 (vb) i've just created a page that, in the page load event, retreives a number of records from the database.

as each record is read into a dataset, a new accordon panel is created. the panel header displays the fldName and the panel content displays the fldContent from the table.

this all works great. the issue i'm having is that it currently displays all the records (approx 200) and i only want 10 records displayed at a time.

my question is, is there somehow a way to implement paging? i found the following article:

http://rolf-cerff.de/blogs/dotnet/archive/2007/03/08/ajax-control-toolkit-paging-with-databound-accordion-control.aspx

but i'm not familiar enough with C# to understand.

also, any idea if paging for the accordion is in the works?

thanks all.

You can use a paged data source...

Basically, create a datatable from your recordset, and then...
Dim pds As New PagedDataSource
pds.DataSource = (whatever then dataset is called).Tables(0).DefaultView
pds.AllowPaging = True
pds.PageSize = 10
pds.CurrentPageIndex = curpage (passed into the databind sub, optional value that = 0 at first)
CurrentPage (see below) = pds.CurrentPageIndex + 1

What I do is to create a viewstate item called CurrentPage to keep track of the pages...
Public Property CurrentPage() As Integer
Get
Dim o As Object = Me.ViewState.Item("_CurrentPage")
If o Is Nothing Then
Return 0
Else
Return o
End If
End Get
Set(ByVal value As Integer)
Me.ViewState.Item("_CurrentPage") = value
End Set
End Property

You can then have linkbuttons to guide through pages... Just rebind using your sub and pass in CurrentPage as the curpage to advance or CurrentPage - 1 to go back.

Dynacly add scriptmanager when needed?

Hi,

I'm trying to create a Web User Control that uses asp.net Ajax. I'd like it to find out if a scriptmanager already exists in the page and, if not, add ti dynamically. Would such a thing be possible?


Thanks in advance for any help.


Regards,

Stefan

Yes its possible, you can check if ScriptManager is registered. FindControl(); or you can added it in the Master Page

http://forums.asp.net/thread/1441992.aspx

http://forums.asp.net/thread/1436775.aspx


Thanks for your quick reply. But how would I use FindControl if I don't know what the name of the scriptmanager would be?

I'm thinking of a situation where my control gets used in combination with other ajax controls, or gets used multpile times on a form. (Actually, my control would be a DotNetNuke module)

Any ideas?


If you didn't change it ScriptManager1


I know, but the hard thing is, that all controls get added to the page dynamically by DotNetNuke. This means I'm pretty sure the name won't be ScriptManager1...

So if there's no other way than to use findcontrol, the only option would be to add the ScripManager to the page itself somehow.


Thanks for your help.



hello.

you can get a reference to the ScriptManager control by using the static GetCurret method. If there's already a ScriptManager on the page, you will get a non null value.

I've put together an example ofUsing Control Adapters to automatically attach AJAX Extenders to ASP.NET Controls, which isn't exactly what you want, but there is code for walking through the controls on a page to see if there is already a ScriptManager or ScriptManagerProxy ...

http://damianblog.com/2006/11/16/adapters-and-extenders/

Damian


hello.

hum...why are you going through a cicle to get the scriptmanager control?


Because I'm doing it from an HttpModule ... and also because I didn't know of the static method :-)

Not sure if it will work in the module though ... will have a go.

Damian


hello.

well, i guess it might not work if you haven't instantiated the master page (which is easily solved by just "touching" the property)


Hi again, it's been a while since I had time to figure this thing out, but your answers look promising. Thanks a lot so far.

Dydfunctional behavior of the control HoverMeuExtender

Hi

With the ajax control HoverMenuExtender
i have a problem.


After have launch the page in Internet Explorer
with the onmouseover event on the linkbutton (as opportunely setted)
appears the popup.


The dydfunctional behavior is that
justlaunch the page,
little moments after than it opens the tab,
all the popups relative at the controls HoverMeuExtender
they open for some moments and then they close.
The effect isunpleasant.

Happen at you too?

Here are some sample codes about ajax:HoverMenuExtender for your reference.
<div>
<ul>
<li>
<asp:LinkButton runat="server" id="lnkParent" text="Parent Menu Item"/>
</li>
<asp:panel runat="server" id="pnlChild">
<ul>
<li>Child Item 1</li>
<li>Child Item 2</li>
</ul>
</asp:panel>
<ajax:HoverMenuExtender ID="hoverMenu"
PopupControlID="pnlChild"
TargetControlID="lnkParent"
PopupPosition="Bottom"
runat="server" />
</ul>
</div>
Wish the above can help you.

Dyanmically adding TabPanels in TabContainer Control

Hi,

I have added the TabContainer control in my page.

the problem is If i add TabPanel Dynamically in TabContainer, these TabPanels do not appera in rendered page.

But if i add one TabPanel at design time and then add other TabPanels dynamically then they appear in page.

I am using the ControlToolKit release in May.

Hi,

It's hard to tell why from your description. And I made a sample, please try it and compare it with your code.

protected void Page_Load(object sender, EventArgs e)
{

AjaxControlToolkit.TabPanel tbpanel = new AjaxControlToolkit.TabPanel();
tbpanel.HeaderText = "Tab 01";
tbpanel.Controls.Add(new TextBox());
Label lb = new Label();
lb.Text = "Content";
tbpanel.Controls.Add(lb);
TabContainer1.Tabs.Add(tbpanel);

}

Hope this helps.

Dyanimc TextBoxWatermark in GridView Pager Template

I have a textbox in my gridview pager template to allow the user to enter a page number to jump to. I would like the watermark to read Page X of Y. I tried to set the watermark text on the GridView_DataBound event, but that doesn't work.

My guess is this occurs because most (if not all) AJAX controls render client scripts durning the preload event and the databound event executes long after the preload. Is this correct? Is this by design? Will AJAX controls always render in the preload event?

Is there a workaround I could use to generate thePage X of Y for the watermark via javascript or something?

Thank you for your assistance

This should work - have a look at the DataBinding.aspx page in the ToolkitTests directory for an example. If you're still stuck, please post a complete, self-contained sample demonstrating the issue. Thanks!