Showing posts with label event. Show all posts
Showing posts with label event. Show all posts

Wednesday, March 28, 2012

How do I trigger an UpdatePanel from the ItemCommand event of a data-bound Accordion?

Greetings, clever ASP.NET AJAX users.

I have a data-bound Accordion with a Button in each header. Cliking the button changes a label inside an UpdatePanel. But I don't want a full postback when the Button is clicked. I just want the UpdatePanel itself updated.

I have tried registering the ItemCommand event of the Accordion as a trigger, but I get this error message, which I don't understand:

Control with ID 'accAccordion' being registered through RegisterAsyncPostBackControl or RegisterPostBackControl must implement either INamingContainer, IPostBackDataHandler, or IPostBackEventHandler.

Here is my code:

 <asp:UpdatePanel ID="upUpdatePanel" runat="server" ChildrenAsTriggers="true" > <ContentTemplate> <div style="border:1px solid black;"> Name: <asp:Label ID="lblName" runat="server" /><br /> <asp:Button ID="btnChange" runat="server" OnClick="btnChange_Click" Text="Inside Update Panel"/> </div> </ContentTemplate> <Triggers> <asp:AsyncPostBackTrigger ControlID="accAccordion" EventName="ItemCommand" /> </Triggers> </asp:UpdatePanel> <br /> <ajaxtoolkit:Accordion ID="accAccordion" runat="server" RequireOpenedPane="false" OnItemDataBound="accAccordion_ItemDataBound" OnItemCommand="accAccordion_ItemCommand"> <HeaderTemplate> header: <asp:Button ID="btnChange" runat="server" CommandArgument="Inside Update Panel" /> </HeaderTemplate> <ContentTemplate> content:<br /> </ContentTemplate> </ajaxtoolkit:Accordion>
public partialclass _Test : System.Web.UI.Page{protected string[] aNames = {"foo","bar","baz" };protected void Page_Load(object sender, EventArgs e) {this.accAccordion.DataSource =this.aNames;this.accAccordion.DataBind(); }protected void btnChange_Click(Object sender, EventArgs e) {this.lblName.Text =this.btnChange.Text; }protected void accAccordion_ItemDataBound(Object sender, AjaxControlToolkit.AccordionItemEventArgs e) {if (e.AccordionItem.ItemType == AjaxControlToolkit.AccordionItemType.Header) { Button btnChange = (Button)e.AccordionItem.FindControl("btnChange"); btnChange.Text = e.AccordionItem.DataItem.ToString(); btnChange.CommandArgument = btnChange.Text; } }protected void accAccordion_ItemCommand(Object sender, CommandEventArgs e) {this.lblName.Text = e.CommandArgument.ToString(); }}

Obviously if I remove the trigger the error goes away, but then I don't get partial page rendering. I tried adding code to the ItemDataBound event of the Accordion to register the Button with the ScriptManager as an AsyncCallBack or whatever it is, and then added code to the ItemCommand event to call the Update() method of the UpdatePanel, but that doesn't work either -- I still get a full postback.

Any ideas?

If it's not feasible to trap the ItemCommand event of the Accordion or the Click event of the Button, is there a more exotic solution that would let me trigger the UpdatePanel from client script? I would need to be able to somehow pass the CommandArgument from the specific button that was clicked...


FYI, I worked around this problem using the approach described here:http://weblogs.asp.net/rajbk/archive/2007/01/21/refresh-updatepanel-via-javascript.aspx

I used SuppressHeaderPostBasks="true" on the Accordion, then for each Button in the Accordion Pane's header, I used the OnClientClick property to set the value of a hidden input element inside the update panel, then call the __doPostBack method pointing at that element. In the codebehind, I trapped the Change event of the hidden input element and did my processing.


I have an updatepanel inside an Accordion and I think you might have the solution for my problem, but I don't understand you process.

I would be grateful if you could help me.

Here's my code;

codebehind

protectedvoid Page_Init(object sender,EventArgs e)

{

Accordion1.FindControl("nothing");

LinkButton UserLink = Accordion1.FindControl("UserLink")asLinkButton;

ScriptManager.GetCurrent(this.Page).RegisterAsyncPostBackControl(UserLink);

//Creates a new async trigger

AsyncPostBackTrigger trigger =newAsyncPostBackTrigger();

//Sets the control that will trigger a post-back on the UpdatePanel

trigger.ControlID ="UserLink";

//Sets the event name of the control

trigger.EventName ="Click";

//Adds the trigger to the UpdatePanels' triggers collection

UpdatePanelUser.Triggers.Add(trigger);

}

protectedvoid Page_Load(object sender,EventArgs e)

{

}

protectedvoid UserLink_Click(object sender,EventArgs e)

{

//UpdatePanel getUserPanel = UserPanel.FindControl("UpdatePanelUser") as UpdatePanel;

//ScriptManager.GetCurrent(this.Page).RegisterAsyncPostBackControl(getUserPanel);

String userPanelPath ="~/CMS/_admin/_components/CMS_controls/admin_controls/UserPanel.ascx";Control userPanel = Page.LoadControl(userPanelPath);

PanelUser.Controls.Add(userPanel);

UpdatePanelUser.Update();

}

aspx

<ajaxToolkit:AccordionID="Accordion1"runat="server"HeaderSelectedCssClass="AdminPanelHeaderSelected"RequireOpenedPane="false"SuppressHeaderPostbacks="true"SelectedIndex="0"HeaderCssClass="AdminPanelHeader"ContentCssClass="AdminPanelContent"FadeTransitions="true"FramesPerSecond="40"TransitionDuration="250"AutoSize="none">

<Panes>

<ajaxToolkit:AccordionPanerunat="server"ID="Home">

<Header>

<ahref=""onclick="return false;">Home</a>

</Header>

<Content>

</Content>

</ajaxToolkit:AccordionPane>

<ajaxToolkit:AccordionPanerunat="server"ID="UserPanel">

<Header>

<asp:LinkButtonID="UserLink"runat="server"OnClick="UserLink_Click">User panel</asp:LinkButton>

</Header>

<Content>

<asp:UpdatePanelID="UpdatePanelUser"runat="server"UpdateMode="Conditional">

<ContentTemplate>

<asp:PanelID="PanelUser"runat="server">

</asp:Panel>

</ContentTemplate>

</asp:UpdatePanel>

</Content>

</ajaxToolkit:AccordionPane>

<ajaxToolkit:AccordionPanerunat="server"ID="STATS">

<Header>

<ahref=""onclick="return false;">Statistics</a>

</Header>

<Content>

</Content>

</ajaxToolkit:AccordionPane>

<ajaxToolkit:AccordionPanerunat="server"ID="GroupEmails">

<Header>

<ahref=""onclick="return false;">Group Email</a>

</Header>

<Content>

</Content>

</ajaxToolkit:AccordionPane>

<ajaxToolkit:AccordionPanerunat="server"ID="Errors">

<Header>

<ahref=""onclick="return false;">Error reporting</a>

</Header>

<Content>

</Content>

</ajaxToolkit:AccordionPane>

</Panes>

</ajaxToolkit:Accordion>

Thanks.

How do I trigger a script to run when a PopupControl gets hidden?

To put it another way: How do I trigger a script to run when a PopupControl gets hidden?Smile

Seeing as the control toolkit handles all the event trapping and so on, I don't know what event to trap and how. Anyone know?

Hi,

the ModalPopup exposes an OnCancelScript property. You can set this property to the script that will be executed when the popup is dismissed.


Hmm ... if I was using a ModalPopup that would be a great tip, but I'm using a normal PopupControl. I've found a dirty trick - the animation property allows a javascript routine to be called when the popup closes. Initially I tried using a javascript _doPostBack to run a server-side routine, but I couldn't get that to work, so I did the whole thing client side instead. It may not be the prettiest way to do it, but hey, it works.

How do I know the AJAX load is complete?

I have several webservice proxies set up and some event wiring that is occurring in the Application.Load client side Ajax event. Is there a property somewhere that I can query to determine if the loading of all Ajax controls and initialization is setup and complete.

I have a client side event that displays a modal popup using a WebService proxy. But when the users click on the button before the Ajax initialization is complete there is a script error. Right now I am checking typeof( WebService.Proxy) to "undefined" to know whether I should execute the method, but a variable I could query would be much better.

Would it be preferable to disable the button by default -- then in app load, enable it?


That is a good suggestion. I could use that method in some situations. However, some of my events are mouseover events and link click events. There will be several on the page and it would be beneficial to have a single interface to consistently determine if I could execute my event script. From the user experience side, most users won't click a button until Ajax has finished loading anyway and I'd hate to distract them with UI elements flickering when they are activated.

In some cases, I would like set a timeout that could poll the app load complete bool and continue firing the event.


I just noticed in Beta 2 the external script references are loaded asychronously. This presses my need for a "done loading javascript file" message, or do you suggest putting this "check" in each javascript object file?


The way the asychronous loading feature is designed, you can be assured that all controls and instantiated and initialized by the time you get the Sys.Application object's "load" event. It is during the processing of the "init" event that all the asynchronous loading work is completed. To ensure that a piece of your code runs AFTER this, you can do the following:

Sys.Application.add_load(function() { anotherFunctionCall(); });

The code above ensures that you can run something with the confidence that all the controls, scripts, etc. have been loaded and initialized.


Preferably you would hookup your event handlers from pageLoad (aka app load). That way, if the user does something like mouse over before the page is ready, nothing happens. No need to check for something being loaded or not.


Thanks, that makes sense. I'm trying to use the extender style javascript object to wire up the event handlers and I think it is going to work out well.

How do I invoke a suitable event on the client?

I have two TextBoxes above a GridView. The GridView is wrapped in an UpdatePanel and both TextBoxes trigger an ajax GridView refresh OnTextChanged.

This is my problem. The user may sometimes leave nothing in a TextBox - when that happens I assume they mean zero, so I want to put the value of '0' back into the TextBox (which the user has removed, by deleting the entire content of the TextBox). See the javascript: restoreTextBox() function below. What event is available for me to do this and can I just invoke the event or do I need to inherit something. I have tried beginRequest() or pageLoaded() but nothing happens.

PS: The txtAssetPc_TextChanged() server-side method is working fine to update the GridView. I just want to know how I can use a suitable client event.

aspx Code only below (the server code is missing as it is not relevant to this problem).


<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true">
<Services>
<asp:ServiceReference Path="~/RedirectService.asmx" />
</Services>
</asp:ScriptManager>
<asp:ValidationSummary ID="vsFunds" runat="server" ValidationGroup="TextPC" DisplayMode="BulletList" ShowSummary="true" /><br />
Equities ≥<asp:TextBox ID="txtEquities" runat="server" Text="0" CssClass="text" MaxLength="3" ToolTip="Enter minimum percentage value of Equities (0 - 100)" OnTextChanged="txtAssetPc_TextChanged" AutoPostBack="true" />% <asp:RangeValidator ID="rvEquities" ControlToValidate="txtEquities" runat="server" ErrorMessage="Valid range for Equities is 0-100" Type="Integer" MinimumValue="0" MaximumValue="100" ValidationGroup="TextPC" /><br />
Fixed Income ≥<asp:TextBox ID="txtFixedIncome" runat="server" Text="0" CssClass="text" MaxLength="3" ToolTip="Enter minimum percentage value of Fixed Income (0 - 100)" OnTextChanged="txtAssetPc_TextChanged" AutoPostBack="true" />% <asp:RangeValidator ID="rvFixedIncome" ControlToValidate="txtFixedIncome" runat="server" ErrorMessage="Valid range for Fixed Income is 0-100" Type="Integer" MinimumValue="0" MaximumValue="100" ValidationGroup="TextPC" />

<asp:UpdatePanel ID="upAssetExposure" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView ID="gvAssetExposure" runat="server" AutoGenerateColumns="False" DataKeyNames="PensionFundID"
AllowSorting="True" AllowPaging="True" PageSize="50"
OnRowDataBound="gvAssetExposure_RowDataBound" OnPageIndexChanging="gvAssetExposure_PageIndexChanging" OnSorting="gvAssetExposure_Sorting" >
<PagerSettings Mode="NumericFirstLast" />
<Columns>
<asp:BoundField HeaderStyle-CssClass="ResultsHeading" ItemStyle-CssClass="tdCol32" NullDisplayText="N/A" DataField="FundName" HeaderText="Investor" SortExpression="FundName" />
<asp:BoundField HeaderStyle-CssClass="ResultsHeading" ItemStyle-CssClass="tdCol12" NullDisplayText="N/A" DataField="TotalFundAssetsSterling" HeaderText="Total Fund Assets (GBP)" SortExpression="TotalFundAssetsSterling" DataFormatString="{0:GBP ###,### m; N/A}" HtmlEncode="False" />
<asp:BoundField HeaderStyle-CssClass="ResultsHeading" ItemStyle-CssClass="tdCol12" NullDisplayText="N/A" DataField="Equities_Percent" HeaderText="Equities (%)" SortExpression="Equities_Percent" DataFormatString="{0:##; N/A}" HtmlEncode="False" />
<asp:BoundField HeaderStyle-CssClass="ResultsHeading" ItemStyle-CssClass="tdCol12" NullDisplayText="N/A" DataField="FixedIncome_Percent" HeaderText="Fixed Income (%)" SortExpression="FixedIncome_Percent" DataFormatString="{0:##; N/A}" HtmlEncode="False" />
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="txtEquities" EventName="TextChanged" />
<asp:AsyncPostBackTrigger ControlID="txtFixedIncome" EventName="TextChanged" />
</Triggers>
</asp:UpdatePanel>

<script type="text/javascript">
var aTxt = ['<%txtEquities.ClientID%>','<%txtFixedIncome.ClientID%>'];
function restoreTextBox(){
for (var e=0; e < aTxt.length; e++){
var txtBox = document.getElementById(aTxt[e]);
if (txtBox.value == '')
txtBox.value = '0';
}
}
</script>

Just add onblur="restoreTextBox();" to your textboxes.

Monday, March 26, 2012

How do I Databind to DropDownListBox with button Onclick

Hi I have javascript calling a webservice which is loading a dataset from an onclick event, which opens a popup window collects information and returns to the main page. I want to just load the data collected from the popup and update the dropdownlist without a postback.

The dataset is loaded and ready to go, I'm not sure how to bind the ds to the dropdown at this point.

Thanks in advance for the help!

Hi

You have an option of populating the DDL using javascript itself by loading the select with options array. But at the cost of not known to the server and not present in view state. If that's okay you can go with that otherwise the good deal would using ajax to load


How would I use ajax to load the dropdownlistbox?


Hi,

Based on my understanding, you opens a popup window to collects information,then you load a dataset based on those information.Where are you loading the dataset? In the popuppage?In the main page?

If you load the dataset in the popup page, It is hard to post your dataset to your main page.

If you just post the collected information to your main page and then load your dataset in the main page, you can do it like this:

place your dropdown contorl in a updatepanel;

pass the collected infoemation to the main page and fire a Ayncpostback to the updatepanel(Loading data from popup to parent window without refreshing the parent window.)

Best Regards,


The update panel will not work as I have 8 independent buttons that need to re populate the different dropdowns on the Main Screen when the Popup closes. Not all the independent buttons are effect the dropdowns at the same time. Is there an extender available that can perform the databind?

Thanks in advance


8independent buttons?

I don't think it is a good design.

Would you please change it?

As far as I know, still no such extender that can perform the databind in that way.


I will create my own extender. Comments on the design are not appreciated, as they are client dictated, and real world...


Hi,

Just a comment...

I think you can pass 8 values to the main page by using "window.opener.document.forms["form1"].elements["xxx"].value = ''".

Happy coding:)

Saturday, March 24, 2012

How do I bind an event to a custom Javascript function?

So I'm tyring to do this in xml-script if possible. What I'm looking for is how to fire a javascript function I define, but declare it in the <completed></completed> tags of my <webMethod>. I did it in a roundabout way by binding it to an html control and applying a custom transform to that html control, but that feels like cheating. Any advice? Ideally it'd look something like:

<completed>

<invokeMethod target="MyJSFunction" method="invoke">

<bindings>

<binding id="something" dataContext="myWebMethod" datapath="result" property="parameters" propertyKey="inputVariable" />

</bindings>

</invokeMethod>

</completed>

But of course that's not quite right as I tried it and it didn't work...

Ok, I managed to solve this, but I'd like to know if there's a way to solve it w/o resorting to what I did. First, I just used the completed attribute of the <pageMethod> (see my .js extension athttp://forums.asp.net/thread/1342638.aspx at this point in the discussion, though, assume it's a serviceMethod, as the functionality is the same). So, my xml-script worked in this fashion:

<pageMethod method="MyMethodName" id="MyMethodId" completed="CustomJavascriptFunction">

<bindings>

<binding to input stuff />

</bindings>

</pageMethod>

That all worked, except that the eventArgs object being passed back as part of the 'completed' event was a Sys.EventArgs.Empty object, which I figured out after iterating over the properties and then digging into the .js again. For my solution, since I was using my custom 'Com.VelocityDataSolutions.PageMethodRequest' class anyway, I just changed the onMethodComplete function to pass the result variable to the target function. to do that I changed:

target.completed.invoke(target,Sys.EventArgs.Empty);

to

target.completed.invoke(target,result);

It works like I want now, my event handler grabs teh eventArgs object to use for its processing. I might change it to pass a more complex object (e.g. passing all the variables instead of just the result), but for now it works.

My real question, though, is did I have to go through all this? lol... If I wanted to do the same thing w/ a serviceMethod and didn't wantt o mod the atlas.js or subclass or anything, is there a way to pass the web service's output string to the event handler in declarative markup?

How do execute a server-side click event for a ModalPopupExtender?

I have created a modal popup to show up during page load. It is my logon dialog box. Anyways, I have set the OkControl property to my logon button to execute some codes through the ModalPopupExtender control staticly and dynamically through Page_Load but both didn't work..

What is my problem?

Thanks!

Ok, I follow the flow from this person website.http://blogs.vertigosoftware.com/alanl/archive/2006/07/25/Creating_a_Confirmation_Using_the_ModalPopup_Extender.aspx It works with a button.

I want to use the SHOW event when the page load but it doesn't work. It seem like it is not rendering the javascript or couldn't find it.

What is my problem?


Hi,

Have you tried this link?

http://blogs.msdn.com/phaniraj/archive/2007/02/20/show-and-hide-modalpopupextender-from-javascript.aspx

How do a postback on Tab change (ajaxToolkit:TabContainer)

Please help - very simple question.

From documentation onajaxToolkit:TabContainer

TabContainer Properties

ActiveTabChanged (Event) - Fired on the server side when a tab is changed after a postbackOnClientActiveTabChanged - The name of a javascript function to attach to the client-side tabChanged event

When tabs changed, I need to know what tab was changed and populate the related dynamic content.

I have the code (see below) wher OnActiveTabChanged="TabChangedServer" never gets fired and do a postback on Tab change. How can I make it to do a postback!?

<ajaxToolkit:TabContainer runat="server" ID="Tabs" OnClientActiveTabChanged="ActiveTabChanged" OnActiveTabChanged="TabChangedServer" >

Thanks

Nat

I found a solution myself. See my post athttp://forums.asp.net/thread/1554862.aspx

Me too!


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

How can Rating Control triggers a event where i click the CurrentRating?

a Rating Control Question

when i clicked the star what was not CurrentRating, it triggered a Changed event,
but i clicked the CurrentRating star, nonthing happened.

now, i'm writting a project. it's needed to show a rating of a item, and allow users to rate it.
i encountered a trouble, user can't rate by the same rating

for example, the current rating is 3, a user wants to rate by 3, but no event been triggered, because Rating control only has Changed event.
if rating were not changed, no event occured.

how can i resolve the problem? write a new control class to extend Rating? or other easier methods?

hi, can someone help me ?

How can i use Comet with Asp.Net?

Im writing basic chat application and i want to useComet technique.
Im trying something like that but when thread Sleep, all event waiting end of sleep. How can i use Comet technique with Asp.Net?

void Page_Load(object sender, EventArgs e) {while (Response.IsClientConnected) {if (newMessage) { Response.Write(newMessage); } System.Threading.Thread.Sleep(1000); } }

It's much more complex than that.

The only C# implementation I've seen is:

http://sourceforge.net/projects/emergetk/

But it's experimental, and looks like a discontinued project.

There is a commercial solution for that, called Lightstreamer (google for it). They are working on this for more than 5 years, and they have a solid server for comet development. But they charge good money for their product.


I am currently working on an affordable version of server push for asp.net.

When contacting the earlier mentioned 'lightstreamer', I received a qoute for US$70.000,-

I guess it was better to make it myself :)

The site is officially not up and running yet, but take a look at the samples onhttp://www.pushasp.net.

These samples also contain the code used.

If you want to play around with the conrols, they should be available for download somewhere this week.

regards,

Arnold


Lightstreamer Moderato has been released last month and is completelyfree of charge for any kind of use.

More info atwww.lightstreamer.com

The ASP.NET AJAX demo is available fromhttp://www.lightstreamer.com/atlasDemo.htm

Cheers




offcourse the answer is PokeIn comet ajax library for asp.net ..



offcourse the answer is PokeIn comet ajax library for asp.net ..



offcourse the answer is PokeIn comet ajax library for asp.net ..



offcourse the answer is PokeIn comet ajax library for asp.net ..

Wednesday, March 21, 2012

How can I reload all UserControls when the event fires in one of them(.ASCX) ( inside the

I have 3 UserControls on a page inside the same UpdatePanel.
When the event fires in one them (Voting control), both others should be updated(blocked for user = 'Disabled').
How should I reload those other UserControls? They are reloaded only after the whole Page is reloaded, so the data are lost by this moment

Hello,

In your code-behind, first remove the controls and then add them, But if you can better explain a bit more what you wanna do, we can help more.

But if your user controls are inside updatepanel only thing which will update is what you changing from code behind. So are you changing other user controls from code behind ??

how can i know which updatepanel in multiple updatepanels at BeginRequest event

hello ,

I have two updatepanels . updatepanel1 and updatepanel2 . updatepanel1 trigger when button1 click . And then updatepanel2 trigger when button2 click . I add one client side event like this

Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequestHandler);

function beginRequestHandler(sender,args)

{

here . how can i know which updatepanel request ? because i want to do some when updatepanel2 request .

Please help me . show me with sample code .

Any post will be appreciated .

Thanks in advance.

kmhsad.

Why are you trying to track which updatepanel is updating when you can just handle the button that caused the update?


Hello ,

Thank you for your replied . i got idea . I am new for ASP.net . i didn't consider this idea before .

thank