Showing posts with label user. Show all posts
Showing posts with label user. Show all posts

Wednesday, March 28, 2012

Multiple Postbacks for AJAX

OK...I'm trying to think of the best solution for this situation:

I have an asp.net AJAX enabled website where the user can run complex queries off my SQL Server database. Some of these queries can last quite a few minutes to complete. What I want to happen is when the user clicks a button to run the query, the user can still move around the website while the query is running. And when the query is done, it basically alerts the user it is finished (by updating a label on the site, for example). So, I tried to do this in AJAX, but the problem is (as far as I understand it) is that, by default, the last postback takes precedence, so that if the user clicked another button after he clicked the run query button, the query can not post back to the site saying the query is done.

So I have a couple of questions:

1) Is there anyway for the site to respond asynchronsly to multiple postbacks?

2) If I make multiple postbacks, will all the calls still finish processing? Is it only that it can't post anything back to the server? For example, if the user ran a query that inserted rows into a table, and he clicked somewhere on the page, will the first postback still finish to completion?

3) Would any sort of multi-threading work in my example?

Thanks for any responses!!

-Howie

hello.

well, yes, you can, for instance, make several web service calls. you cannot do the same thing with an UpdatePanel since the last postback will, by default, cancel the previous one. what i think you should do is built some sort of queuing for packaging the client queries and sending them to the server. and i also think that you should use web services instead of updatepanels :)


Hi, thanks for the response. When you say that the last postback will cancel the previous ones, do you mean that it will cancel the query midway through? (excuse me if I'm being naive). Or do you mean that my code will still execute OK (that if the user wanted to insert rows into the table, that it will still do so without interruption), but I just can't post back a result to the site? Also, what do you mean I can make several web service calls? Would you be able to point me to a site I can read up more about it? (I know what web services are...I just don't know exaxtly what you'te referring to).

I really appreciate your help.

multiple tabs which get dynamically filled with user controls

Hey guys, i'm new to this stuff. I've searched for hours but couldn't find an appropriate solution for my problem. i'm sure that it's not a big deal, but somehow i can't figure out how to solve this.

the problem is the following:

I have a website with a menu and other not so importent content on it. There is also a TabContainer inside an UpdatePanel.

I want to implement multiple Tabs which contain a single UserControl for each Tab. These Tabs should be add -and removable. So when i click on button of the menu a new Tab opens up and gets filled with the correct User Control.

I've tried the following:

Dim myTab As New AjaxControlToolkit.TabPanel
Dim Member As System.Web.UI.Control = LoadControl("~/Member.ascx")
myTab.Controls.Add(Member)
TabContainer1.Tabs.Add(myTab)

Somehow i get a tab, but i have to click on the tab to display my user control at the same time i get an ArgumentOutOfRangeException followed by a time out.

Any idea what i've done wrong?

thanks in advance!

Need to see your code if possible


Yes, please show us a simple repro. It's hard to tell why from your current description.


It's more a question in general. Is it correct that i only place the tabcontainer on my page and add the tabpanels dynamically via my code behind file?..like already mentioned in the post before:

Dim myTab As New AjaxControlToolkit.TabPanel
Dim Member As System.Web.UI.Control = LoadControl("~/Member.ascx")
myTab.Controls.Add(Member)
TabContainer1.Tabs.Add(myTab)

What else do I have to take care of when I want to implement add and removeable tabs? i think it's not possible to add and remove updatepanels at runtime right?

I figured out that the "ArgumentOutOfRangeException" disapears if I put the code above in the page init event, but that doesn't really help me at all, because the Tabpanels should be created when i click on one of my menu buttons.

thanks in advance!


Generally, the code and logic you've shown is correct.

I'm asking for a simple repro because I'm not sure where is the exception thrown, and suspect this might have something to do with the page life cycle.


I fixed the exception by adding the code into the page init event (the user control was loaded into a tab before it existed). i'm sure your're right that it has something to do with my page life cycle. The question is: is it possible to remove and add the same tab during the page life cycle?

Thanks for the quick reply!


muffos:

The question is: is it possible to remove and add the same tab during the page life cycle?

Yes, of course you can.


Hallo again,

The page works perfect if I add the TabPanel with the UserControl inside during the page_init event, but that is not a fitting solution. If I put the code that adds the Tabpanel in a button click event the tab is not displayed and I get an error like the following (translated error message):

An Error occured during the validation of the ViewState-MAC. If this apllication was hosted by a webfarm or a cluster make sure that the <machineKey> configuration indicates the same validationKey and validation algorithm. AutoGenerate can not be used in a cluster.

Any idea why i get this error?

Could you give me a short example of a aspx page where you at and remove ajax tabs by clicking on a button?

I really appreciate your help!


I found an older thread where they were discussing the same problem that I have right now.

http://forums.asp.net/p/1077423/1595745.aspx

They didn't find a solution either. Ideas on this?!?!


<%@. 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 LinkButton1_Click(object sender, EventArgs e) { TabContainer1.Tabs.RemoveAt(TabContainer1.ActiveTabIndex); }</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> </div> <ajaxToolkit:TabContainer ID="TabContainer1" runat="server" ActiveTabIndex="0"> <ajaxToolkit:TabPanel ID="TabPanel1" runat="server" HeaderText="TabPanel1"> <ContentTemplate> Tab 1 </ContentTemplate> </ajaxToolkit:TabPanel> <ajaxToolkit:TabPanel ID="TabPanel2" runat="server" HeaderText="TabPanel2"> <ContentTemplate> Tab 2 </ContentTemplate> </ajaxToolkit:TabPanel> <ajaxToolkit:TabPanel ID="TabPanel3" runat="server" HeaderText="TabPanel3"> <ContentTemplate> Tab 3 </ContentTemplate> </ajaxToolkit:TabPanel> </ajaxToolkit:TabContainer> <asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click">Remove Current Tab</asp:LinkButton> </form></body></html>
Is this what you need?

Well, I managed to add one dynamically created tab with a user control inside without getting any error. Somehow i'm not able to add any more Tabs.

Here is my current code:

PartialClass _Default

Inherits System.Web.UI.Page

Private _memberAs System.Web.UI.Control

Private _TestSeite2As System.Web.UI.Control

ProtectedSub Page_Load(ByVal senderAsObject,ByVal eAs System.EventArgs)HandlesMe.Load

TimeLabel.Text = DateTime.Now

EndSub

ProtectedSub LinkButton1_Click(ByVal senderAsObject,ByVal eAs System.EventArgs)Handles LinkButton1.ClickDim myTabAsNew AjaxControlToolkit.TabPanel

TabContainer1.ActiveTabIndex = 0

myTab.Visible =True

EndSub

ProtectedSub LinkButton2_Click(ByVal senderAsObject,ByVal eAs System.EventArgs)Handles LinkButton2.ClickDim myTab2AsNew AjaxControlToolkit.TabPanel

TabContainer1.ActiveTabIndex = 1

myTab2.Visible =True

EndSub

ProtectedSub TabContainer1_Init(ByVal senderAsObject,ByVal eAs System.EventArgs)Handles TabContainer1.Init

If Page.IsPostBackThen

TabContainer1.Tabs.Clear()

_member = LoadControl("~/Member.ascx")

Dim myTabAsNew AjaxControlToolkit.TabPanel

myTab.HeaderText ="Tab 1"

TabContainer1.Tabs.AddAt(0, myTab)

myTab.Controls.Add(_member)

EndIf

//// i know that the following loop doesn't make any sence, it's just the result of my frustration :)

If Page.IsPostBackThen

_member = LoadControl("~/Testseite2.ascx")

Dim myTab2AsNew AjaxControlToolkit.TabPanel

myTab2.HeaderText ="Tab 2"

TabContainer1.Tabs.AddAt(1, myTab2)

myTab2.Controls.Add(_member)

myTab2.Visible =True

EndIf

EndSub

EndClass

//////////////////////and here my aspx page:

<%@.PageLanguage="VB"AutoEventWireup="true"CodeFile="ItellU.aspx.vb"Inherits="_Default"enableEventValidation="false"viewStateEncryptionMode="Never"enableViewStateMac="false" %>

<%@.RegisterSrc="Member.ascx"TagName="Member"TagPrefix="uc1" %>

<%@.RegisterSrc="Testseite2.ascx"TagName="Testseite2"TagPrefix="uc1" %>

<!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.1//EN""http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<htmlxmlns="http://www.w3.org/1999/xhtml">

<headid="Head1"runat="server">

<title>Untitled Page</title>

<linkhref="StyleSheet.css"rel="stylesheet"type="text/css"/>

</head>

<bodystyle="background-color: #e3efff">

<formid="form1"runat="server">

<asp:ScriptManagerID="ScriptManager"runat="server"EnablePartialRendering="true">

</asp:ScriptManager>

<div>

<asp:UpdatePanelID="UpdatePanel1"runat="server"UpdateMode="conditional"ChildrenAsTriggers="false">

<ContentTemplate>

<asp:PanelID="Timer"style="z-index:100; position: absolute; top: 584px; left: 27px"runat="server"Height="50px"Width="125px">

<asp:UpdatePanelID="UpdatePanelTimer"runat="server">

<ContentTemplate>

<asp:LabelID="TimeLabel"runat="server"style="vertical-align: middle; border-top-style: none; border-right-style: none; border-left-style: none; background-color: white; text-align: center; border-bottom-style: none"BackColor="White"Height="25px"Width="180px"></asp:Label>

</ContentTemplate>

<Triggers>

<asp:AsyncPostBackTriggerControlID="Timer1"EventName="Tick"/>

</Triggers>

</asp:UpdatePanel>

</asp:Panel>

<asp:TimerID="Timer1"runat="server"Interval="900">

</asp:Timer>

<tablestyle="z-index: 119; left: 234px; width: 897px; position: absolute; top: -4px; height: 844px; border-left-color: #a9c0df; border-bottom-color: #a9c0df; border-top-style: ridge; border-top-color: #a9c0df; border-right-style: ridge; border-left-style: ridge; border-right-color: #a9c0df; border-bottom-style: ridge;">

<tr>

<tdstyle="width: 437px; height: 443px"valign="top">

<ajaxToolkit:TabContainerID="TabContainer1"runat="server"height="0px"OnInit="TabContainer1_Init">

</ajaxToolkit:TabContainer>

</td>

</tr>

</table>

<asp:LinkButtonID="LinkButton1"runat="server"Style="z-index: 108; left: 10px;

position: absolute; top: 120px;"CssClass="linkbuttonBlue">neue Auftragsdienstleistung

</asp:LinkButton>

<asp:LinkButtonID="LinkButton2"runat="server"Style="z-index: 109; left: 10px;

position: absolute; top: 143px;"CssClass="linkbuttonBlue">GDL Zuordnung

</asp:LinkButton>

</asp:Panel>

</ContentTemplate>

<Triggers>

<asp:AsyncPostBackTriggerControlID="LinkButton1"EventName="Click"/>

<asp:AsyncPostBackTriggerControlID="LinkButton2"EventName="click"/>

</Triggers>

</asp:UpdatePanel>

</div>

</form>

<scripttype="text/javascript">

function setBodyHeightToContentHeight() {

document.body.style.height = Math.max(document.documentElement.scrollHeight,

document.body.scrollHeight)+"px";

}

setBodyHeightToContentHeight();

window.attachEvent('onresize', setBodyHeightToContentHeight);

</script>

</body>

</html>

please remember, that i'm new to this stuff :)

thanks in advance!


What's wrong with your code? I suppose it's working fine.

Two panels are created, and whenever you click on a linkButton, a corresponding tab panel will be actived.

<%@. Page Language="VB" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><script runat="server"> Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load TimeLabel.Text = DateTime.Now End Sub Protected Sub LinkButton1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles LinkButton1.Click Dim myTab As New AjaxControlToolkit.TabPanel TabContainer1.ActiveTabIndex = 0 myTab.Visible = True End Sub Protected Sub LinkButton2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles LinkButton2.Click Dim myTab2 As New AjaxControlToolkit.TabPanel TabContainer1.ActiveTabIndex = 1 myTab2.Visible = True End Sub Protected Sub TabContainer1_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles TabContainer1.Init If Page.IsPostBack Then TabContainer1.Tabs.Clear() Dim _member As New TextBox() '= LoadControl("~/Member.ascx") Dim myTab As New AjaxControlToolkit.TabPanel myTab.HeaderText = "Tab 1" TabContainer1.Tabs.AddAt(0, myTab) myTab.Controls.Add(_member) End If '//// i know that the following loop doesn't make any sence, it's just the result of my frustration :) If Page.IsPostBack Then Dim _member As New TextBox() ' = LoadControl("~/Testseite2.ascx") Dim myTab2 As New AjaxControlToolkit.TabPanel myTab2.HeaderText = "Tab 2" TabContainer1.Tabs.AddAt(1, myTab2) myTab2.Controls.Add(_member) myTab2.Visible = True End If End Sub </script><html xmlns="http://www.w3.org/1999/xhtml"><head id="Head1" runat="server"><title>Untitled Page</title><link href="StyleSheet.css" rel="stylesheet" type="text/css" /> </head><body style="background-color: #e3efff"><form id="form1" runat="server"><asp:ScriptManager ID="ScriptManager" runat="server" EnablePartialRendering="true"></asp:ScriptManager><div><asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="conditional" ChildrenAsTriggers="false"><ContentTemplate> <asp:Panel ID="Timer" style="z-index:100; position: absolute; top: 584px; left: 27px" runat="server" Height="50px" Width="125px"> <asp:UpdatePanel ID="UpdatePanelTimer" runat="server"> <ContentTemplate> <asp:Label ID="TimeLabel" runat="server" style="vertical-align: middle; border-top-style: none; border-right-style: none; border-left-style: none; background-color: white; text-align: center; border-bottom-style: none" BackColor="White" Height="25px" Width="180px"></asp:Label> </ContentTemplate> <Triggers> <asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" /> </Triggers> </asp:UpdatePanel> </asp:Panel><asp:Timer ID="Timer1" runat="server" Interval="900"></asp:Timer> <table style="z-index: 119; left: 234px; width: 897px; position: absolute; top: -4px; height: 844px; border-left-color: #a9c0df; border-bottom-color: #a9c0df; border-top-style: ridge; border-top-color: #a9c0df; border-right-style: ridge; border-left-style: ridge; border-right-color: #a9c0df; border-bottom-style: ridge;"><tr><td style="width: 437px; height: 443px" valign="top"> <ajaxToolkit:TabContainer ID="TabContainer1" runat="server" height="0px" OnInit="TabContainer1_Init"></ajaxToolkit:TabContainer> </td></tr></table><asp:LinkButton ID="LinkButton1" runat="server" Style="z-index: 108; left: 10px;position: absolute; top: 120px;" CssClass="linkbuttonBlue">neue Auftragsdienstleistung</asp:LinkButton> <asp:LinkButton ID="LinkButton2" runat="server" Style="z-index: 109; left: 10px;position: absolute; top: 143px;" CssClass="linkbuttonBlue">GDL Zuordnung</asp:LinkButton> </ContentTemplate><Triggers><asp:AsyncPostBackTrigger ControlID="LinkButton1" EventName="Click"/><asp:AsyncPostBackTrigger ControlID="LinkButton2" EventName="click"/></Triggers></asp:UpdatePanel></div></form><script type="text/javascript">function setBodyHeightToContentHeight() {document.body.style.height = Math.max(document.documentElement.scrollHeight,document.body.scrollHeight)+"px";}setBodyHeightToContentHeight();window.attachEvent('onresize', setBodyHeightToContentHeight);</script> </body></html>

I found a solution, check this out.

it works nearly perfect, but i use a hidden tab to keep my tabcontainer alive. I think this code might help you if you want to implement AJAX Tabs with rich functionality.

PartialClass _Default

Inherits System.Web.UI.Page

Private _memberAs System.Web.UI.Control

Private _TestSeite2As System.Web.UI.Control

Private myTabAs AjaxControlToolkit.TabPanel

Private myTab2As AjaxControlToolkit.TabPanel

Private tabbitabAs AjaxControlToolkit.TabPanelProtectedSub Page_Load(ByVal senderAsObject,ByVal eAs System.EventArgs)HandlesMe.Load

TimeLabel.Text = DateTime.Now

If Session.Item("CreateTab")IsNothingThen

Session.Add("CreateTab",False)

EndIf

EndSub

ProtectedSub LinkButton1_Click(ByVal senderAsObject,ByVal eAs System.EventArgs)Handles LinkButton1.Click

If Session.Item("button1clicked")IsNothingThen

Session.Add("button1clicked",True)

Else

Session.Item("button1clicked") =True

EndIf

If Session.Item("UpdateUpdatePanel")IsNothingThen

Session.Add("UpdateUpdatePanel",True)

Else

Session.Item("UpdateUpdatePanel") =True

EndIf

EndSub

ProtectedSub LinkButton2_Click(ByVal senderAsObject,ByVal eAs System.EventArgs)Handles LinkButton2.Click

If Session.Item("button2clicked")IsNothingThen

Session.Add("button2clicked",True)

Else

Session.Item("button2clicked") =True

EndIf

If Session.Item("UpdateUpdatePanel")IsNothingThen

Session.Add("UpdateUpdatePanel",True)

Else

Session.Item("UpdateUpdatePanel") =True

EndIf

EndSub

ProtectedSub TabContainer1_ActiveTabChanged(ByVal senderAsObject,ByVal eAs System.EventArgs)Handles TabContainer1.ActiveTabChanged

EndSub

ProtectedSub TabContainer1_Init(ByVal senderAsObject,ByVal eAs System.EventArgs)Handles TabContainer1.Init

If IsPostBackThen

TabContainer1.Tabs.Clear()

If Session.Item("CreateTab")Then

tabbitab =New AjaxControlToolkit.TabPanel

tabbitab.HeaderText =""

TabContainer1.Tabs.Add(tabbitab)

TabContainer1.ActiveTab = tabbitab

TabContainer1.ActiveTabIndex = TabContainer1.Tabs.Count

EndIf

If Session.Item("button1clicked")Then

_member = LoadControl("~/Member.ascx")

myTab =New AjaxControlToolkit.TabPanel

myTab.HeaderText ="neue Auftragsdienstleistung"

TabContainer1.Tabs.Add(myTab)

myTab.Controls.Add(_member)

TabContainer1.ActiveTab = myTab

TabContainer1.ActiveTabIndex = TabContainer1.Tabs.Count

EndIf

If Session.Item("button2clicked")Then

_member = LoadControl("~/Testseite2.ascx")

myTab2 =New AjaxControlToolkit.TabPanel

myTab2.HeaderText ="GDL Zuordnung"

TabContainer1.Tabs.Add(myTab2)

myTab2.Controls.Add(_member)

TabContainer1.ActiveTab = myTab2

TabContainer1.ActiveTabIndex = TabContainer1.Tabs.Count

EndIf

If Session.Item("UpdateUpdatePanel")Then

UpdatePanel1.Update()

Session.Item("UpdateUpdatePanel") =False

EndIf

EndIf

EndSub

ProtectedSub CloseTabButton_Click(ByVal senderAsObject,ByVal eAs System.EventArgs)Handles CloseTabButton.Click

If IsPostBackThen

Try

If TabContainer1.ActiveTabIs myTabThen

Session.Item("button1clicked") =False

EndIf

If TabContainer1.ActiveTabIs myTab2Then

Session.Item("button2clicked") =False

EndIf

Catch exAs Exception

Session.Item("button1clicked") =False

Session.Item("button2clicked") =False

EndTry

Session.Item("UpdateUpdatePanel") =True

Session.Item("CreateTab") =True

EndIf

EndSub

EndClass

Multiple UCs on a page

On my page I have two User Controls. One, UC1, has a DropDownList. The other one, UC2, is a list that gets data from a SqlDataSource (datasourcetype=strored procedure), by Repeater.

Whenever the ddl in UC1 is changed, it triggers a function that puts a log record into the database from which UC2 gets the data.

I need the new log record to appear immediately after the selected index of ddl is changed, but it only appears after I refresh the page.

I can't create any triggers for the UpdatePanel of UC1, because the controls are in different UCs.

I tried to use delegates and events, but unsuccessful. My knowledge in that area is limited.

You should be able to use triggers for the update panel even though they are different controls.
Can you post your code?
You can also just refresh the page in code...


Make sure they are both in updatepanels, and set both toUpdateMode="Always". Then, when one updates, the other automatically updates.

Multiple update panels

I had a query regarding multiple update panels.
I have a user control which contains one update panel.This user control contains a hidden textbox .
I am updating the updatepanel on basis of a timer control in javascripts which raises a postback.

I have placed two instances of this user control in another page say for eg. CIndexPage.aspx.
Now the Script manager is also placed in the same page ie CIndexPage.aspx.

Will the two updatepanels wrk independently.

Is the hidden variable shared between the instances of the update panel ?
Becoz the issue here is that even if i pass a value for the hidden textbox contained
in the first Update Panel, still the value gets stored for the hidden
variable in the second instance of the updatePanel.

Can we use Update Panels in a User Control and place multiple instances of the UserControls in a page.

Please if someone cld help me with this.

Thanks in advance.

Regards,
Shweta

hello.

well, the updatepanels will work independently. if you want to get independent refershes, you need to make sure that you've set the update mode of the pannel to conditional.

regarding the hidden field, it depends on how you've injected in the page...


Hi,

My Code is somewhat like this

User Control contains

_____________________________________________________________

<asp:UpdatePanel id=UpdatePanel1 runat=server>
<div id=DivCtrl runat=server >
<asp:HiddenField runat="server" ID="RequestID" Value="0" />
</UpdatePanel>


____________________________________________________________________
There is adiv control which contains multiple hyperlinks.That is done thru .cs file of the Master Control and is dynamically generated.
The hidden filed in placed inside the UpdatePanel and the RequestID is updated on the hyperlink click.

And 2 instances of this user control are placed in the Parent Page.
Also what happens is even though i am clicking on the first User Controls hyperlink (first updatepanel) still the Value is assigned to the second User Controls Hidden Field.

It always updates the last user control.

Why does work in this manner . Also to update the UpdatePanel i am using the timer control and _dopostback method.

Is there an issue with the timer control.Shld that be placed in the ParentPage.

regards,

Shweta


hello.

can you please build a small demo app with a simple user control + page and put it here?


yes sure
------------
User Control Code is as follows for .aspx is as follows
-------------
<script language =javascript>
var l_objtimer="";
l_objtimer =window.setInterval('UPdatePanel',1000);
function UPdatePanel()
{
var obj=get$('<%=RequestID.ClientID%>');
_dopostback("obj",'');
}

function CallDetails(nSerialNo)
{
var obj=get$('<%=RequestID.ClientID%>');
obj.value=nSerialNo;
_dopostback("obj",'');
}
</script>
<body>
<asp:UpdatePanel id=UpdatePanel1 runat=server>
<div id=DivCtrl runat=server >
<asp:HiddenField runat="server" ID="RequestID" Value="0" />
</UpdatePanel>
</body>

------------
end
-------------

------------
User Control Code is as follows for cs is as follows
-------------

In this i dynamically adding a hyperlink whose onclick events call CallDetails(nSerialNo) (in .aspx of user control).
And pass different value to the nSerialNo parameter on the click event.In the event i change the value of RequestID to the the nSerialNo.

------------
end
-------------

------------
Parent Page Code is as follows for .aspx is as follows
-------------
<%@. Register TagPrefix="csc" Namespace="CustomServerControls" %>
<body>
<asp:ScripManager runat=server id=ScriptMgr1 >
</asp:ScripManager >
<csc:CustomServerControls id=CustomServer1 runat=server >
</csc:CustomServerControls>

<csc:CustomServerControls id=CustomServer2 runat=server >
</csc:CustomServerControls>

</body>

------------
end
-------------

This way 2 instances of this user control are placed in the Parent Page.
Also what happens is even though i am clicking on the first User Controls hyperlink (first updatepanel) still the Value is assigned to the second User Controls Hidden Field.

Also if i am placing the usercontrol in a page and call the page thru <script tag by specifying the source it gives me a Syntax error.

Can i call the page in this way.


hello

well, now it's clear!. what you shoud do is change the js code. you should have something like this:

<script language =javascript>
var l_objtimer="";
l_objtimer =window.setInterval('UPdatePanel',1000);
function UPdatePanel(idCtl)
{
var obj=get$(idCtl);
_dopostback("obj",'');
}

function CallDetails(idCtl, nSerialNo)
{
var obj=get$(idCtl);
obj.value=nSerialNo;
_dopostback("obj",'');
}
</script>

where idCtl is the ID of the control (hidden field) you want to use. yep, you'll have to change your code so that it also passes the id of the field when you call the method.

in your code, what's happening is that when you're adding the second user control, it'll add the js methods again, overriding the previous definitions. this means that clicking on the 1st or 2nd user control will always call the latest definition, which points to the id of the last user control you've added to the page. if you perform the changes I've said, this won't happen any more.

Multiple Update Panel Animation Extenders on one page

Hi there!

I'm developing a web user control that contains an Update Panel and uses an Update Panel Animation Extender.
The animation is quite simple: while the panel is updating, it fades out the contents of the update panel and fades in the "please wait while processing..." message...then the animation reverses the process when the panel is Updated. The animation works quite nicely.

The problem I'm facing is when I have more than one of these web user controls on the page at a time (I'm using 8 of these on one page at a time).
If one web user control's update panel does an asynchronous postback, all of the animations are run!

Does anyone know how to get around this problem?

Thanks in advance,

-Frinny

Hi,

Would you please provide with any code of ypur usercontrol?

Or create a simple repro of this problem?

Thanks,


I forgot that I had posted this question.
I found the solution to my problem a while ago.

The problem I was describing is not actually a problem, it is how the UpdatePanelAnimationExtender works.

Anyways, to get around this problem I ended up using regular Animations instead of the UpdatePanelAnimationExtender.

Cheers!

Monday, March 26, 2012

MultiView, User Controls, PopupControlExtender

I have a webpage containing a MultiView. I put a user control in every view of the MultiView. From each user control, I use the ModalPopupExtender to open another user control, which contains fields for entering dates. I then use the calendar control and PopupControlExtender to select date.

It works fine when only one user control in the modal popup window has the calendar control and the PopupControlExtender. If more than one user controls opened with the modal popup extender have the calendar control and the PopupControlExtender, none of them works. In the latter case, I can still popup the calendar, but it doesn't allow me to select date, and it doesn't close. The calendar would dispear if I click outside the calendar area. But then I can't close the window containing the user control opened with the modal popup extender.

Anyone has similiar experience?

Please try your scenario with the recently available61020 release of the Toolkit (and ASP.NET AJAX Beta 1). If the problem persists, then please reply with acomplete, self-contained sample page that demonstrates the problem. Thank you!

MutuallyExlcusiveCheckBox problems after postback

Hello all.

I have added a MutuallyExlcusiveCheckBox extender to my user controll to make sure just one checkbox is checed at the time. My user controll is then added to a web form, and it works great until I do a post back. When I do a postback I can check more than one checkbox. Is this a bug or something I do wrong. I set the key runtime, would this have something to say?

Endre

A small update:

I have just figured out that none of my ajax stuff works!

So now i think the problem might be related to the use of UpdatePanels on my page. Anyone know something about this?

Endre


Hello again.

This post is just a wast for your time, sorry. My app is a bit f**ked up... I have found some sort of solution by moving the Exlusive controls out of my update panel, the way it should be. I tried to recreate the problem, but couldn't, so I guess the reason was lots of messy code and many developers doing the same thing in different ways.

Endre

My (Un)Modal Popup

I have added a modal popup to my user control. I show the modal popup by registering a startup script in the code-behind of an update panel trigger. The modal popup appears, but it isn't modal. I can click and edit the form fields behind the modal popup. Has anyone seen this happen? Any thoughts on how to fix it?Post code and I might be able to help you

Have you set the BackgroundCSSClass properly? I saw the same behavior and was able to fix it by setting the BackgroundCSS... here's an example of the CSS I used

.modalBackground

{background-color:Gray;filter:alpha(opacity=70);

}


I used below css but still my main page controls can be accessed?

.modalBackground

{background-color:Gray;filter:alpha(opacity=70);

}

This is happening in (Un)Modal fashion, any have solution for this.

Saturday, March 24, 2012

my javascript method not working with update panel

Hi All,

The gridview (inside a user control) i am using in my screen (.aspx page) have a Checkbox column in the end. When i click the checkbox in the header all the checkboxes are selected. (A long javascript code has been written for that in the user control)

Now I have applied a scriptmanager and update Panel on this user control, and since then the javascript which selects all the checkboxes is not working properly.

I would like to know what i can do to resolve this javascript issue. And also would like to know why using the basic tools of ASP.NET AJAX control is stopping my own javascript from firing.

Please Note: On leaving a validation on page, the page postback and shows the validation. After this the javascript of Gridview works fine.

I have tried searching on google, but was not able to find any satisfactory explanation to my problem. It would be great if you people can help me.

Thanks,

Shikha

Please post your source code.


Hi,

Thank you for your post!

It is normal when you place inline javascript in an undatepanel/

For more information and solution, seeUpdatePanel and Rendered (Inline)Javascript

It seems that the UpdatePanel essentially replaces the InnerHTML of a DIV with the delta returned from the server. If you try this yourself you will notice that any javascript elements in the html are not fired.

All javascript registered on the server-side (if you are using .NET) with the ScriptManager is put into a separate section of the returned delta. The atlas runtime obviously then loads these scripts into the document manually.

What if the returned HTML has Javascript tags already rendered in it? Nothing.:(
Such was our predicament and we had no control over the HTML that would be returned to the UpdatePanel (ReportViewer Control). Could we manually load the javascript ourselves when the UpdatePanel returns the payload? As it turns, we could.

You can create script elements on the fly and they get evaluated as you do. Atlas has the ScriptLoader object that will do it for you if your JavaScript is an external reference. Tweaking this idea we got a solution that found all the new Script elements and added them to the document.

If you have further questions,let me know.

Best Regards,

my web service call works from one page, not from the other.

have a user control that uses Atlas to call a web service. I drop
this control on a page in the root directory and it works with no
problem. I then add the control to another control, which is on
another page and it will not work. It does not seem to know what the
webService is.

My web service is in the same project and the ascx control and is named
meterCommunication.asmx in a folder called webService.

The control is a button ond onClick it callas a javascript function
that has the following line for calling the web service:
meterCommunication.sendMessage(meterID, commType, _onRequestComplete);

The error that I get is a javascript error that says:
meterCommunication is undefined

I can't figure out what is different between the two pages. Since this
is on a user control they should be identical.

How does the javascript know what meterCommunication is?
I don't know enough about this to troubleshoot the problem.

You need to make sure that you import the web service proxy, either in your page or in the user control. This is done using:
<scriptsrc="/yourapp/subdir/YourService.asmx/js"type="text/javascript"></script>
Maybe you have that only on the page that works?

Need a way to reemember user selected checkboxes in a gridview in an update panel during a

I'm using ASP.NET 2.0 & Ajax. I have a gridview in an update panel. One of the templated columns in the gridview is a checkbox. In addition, two textboxes provide asynchronous triggers on their "TextChanged" event. I need to remember and re-apply the user selected checkboxes after an asynch postback. I've tried using ViewState as follows:

********************* aspx page code ******************************

<asp:UpdatePanel ID="UpdatePanel1" runat="server" RenderMode="Inline"
OnUnload="GetCheckedStores" OnLoad="SetCheckedStores">
<ContentTemplate>
<asp:Panel ID="StoresPnl" runat="server" Height="50px" Width="608px">
<asp:GridView ID="grvStores" runat="server" AutoGenerateColumns="false" DataMember="DefaultView"
DataSourceID="dsStores" DataKeyNames="Store" EnableTheming="true" Width="400px">
<Columns>
<asp:TemplateField>
<ItemStyle Width="50px" />
<ItemTemplate>
<asp:CheckBox ID="chbStore" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Store" HeaderText="Store #">
<ItemStyle Width="100px" />
</asp:BoundField>
<asp:BoundField DataField="Name" HeaderText="Name">
<ItemStyle Width="150px" />
</asp:BoundField>
<asp:BoundField DataField="BatchCount" HeaderText="Batch Count">
<ItemStyle Width="80px" />
</asp:BoundField>
</Columns>
</asp:GridView>

</asp:Panel>
<!-- ID="StoresPnl" -->
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="txbFromDate" EventName="TextChanged" />
<asp:AsyncPostBackTrigger ControlID="txbToDate" EventName="TextChanged" />
</Triggers>

</asp:UpdatePanel>


******************************* code behind ******************************************

string reportDescription;
string reportCode;
ArrayList checkedStores;

ArrayList CreateCheckedStoresArray()
{
ArrayList result = new ArrayList();
foreach (GridViewRow row in grvStores.Rows)
{
result.Add(false);
}
return result;
}

protected void SetCheckedStores(object sender, EventArgs e)
{
int Ndx = 0;
checkedStores = (ArrayList)ViewState["checkedStoresArray"];

if (checkedStores != null)
{
foreach (GridViewRow row in grvStores.Rows)
{
CheckBox ckbx = row.FindControl("chbStore") as CheckBox;
ckbx.Checked = (bool)checkedStores[Ndx];
Ndx++;
}
}
}

protected void GetCheckedStores(object sender, EventArgs e)
{
int Ndx = 0;
checkedStores = (ArrayList)ViewState["checkedStoresArray"];

if (checkedStores != null)
{
foreach (GridViewRow row in grvStores.Rows)
{
CheckBox ckbx = row.FindControl("chbStore") as CheckBox;
checkedStores[Ndx] = ckbx.Checked;
Ndx++;
}
}
}

protected void Page_PreInit(Object sender, EventArgs e)
{
Page.Theme = Master.Theme;
}

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
checkedStores = CreateCheckedStoresArray();
ViewState.Add("checkedStoresArray", checkedStores);
ReportsPanelVisible();
}
}
*************************************************************************

I was hoping that the "OnLoad" and "OnUnload" attributes of the update panel would execute my code-behind to store/retrieve which checkboxes were checked over an async postback, but this did not work.

I'm not married to this approach, but I do need a clue how to get this done.

Thanks for your help.

To avoid extra effort can you please provide the db related script.


Hi,

If you mean the detailed data source code, data access is done via a Data Access Layer and custom data access objects. I can only post that the DataSourceID="dsStores" is

<mtx:WSDataSource runat="server" ID="dsStores" DataGroup="Report" SubDataGroup="Related">
<SelectParameters>
<asp:ControlParameter ControlID="txbFromDate" Name="DateFrom" PropertyName="Text" />
<asp:ControlParameter ControlID="txbToDate" Name="DateTo" PropertyName="Text" />
</SelectParameters>
</mtx:WSDataSource>

As you can see, this is a custom/propriatary data access. The data returned from this source is quite correct, and the checkbox values are not retrieved from the data base.


Hi,

Based on my understanding, you creat CheckedStoresArray when the gridview is first binded, and then store it in viewstate,when the page is postback,you GetCheckedStores and store them in the Array in viewstate, then update/rebind/change your gridview,then SetCheckedStores according to the value in the array in viewstate.

I think your logic is messed up, just do GetCheckedStores before the gridview rebinding and do SetCheckedStores after the gridview rebinding.

Best Regards

Need async post back from 1 user ctrl to another user ctrl in same master page.

Hi,

I have 3-4 web user ctrl in a Master page. Now this Master Page is being hosted by a page: ViewProductCategories.aspx. Among the userctrls on the MasterPage, I have got an ImageButton (asp:ImageButton) in one of the userctrl (ProductCtrl.ascx). Instances of ProductCtrl.ascx is being loaded dynamically on the ViewProductCategories.aspx dependng on the number of product under a category. So I have to dynamically assign the event handler for the image button click. What I want is: On the click of the asp:ImageButton (AddToCart) there should be a AsyncPostBack that only refreshes the CartCtrl.ascx which is another user ctrl on the same MasterPage, but not the other userctrls on the same master page. Situation is complex. Please let me know if any more info is needed.

Thanks,

Subhadip

Hi

You can check out this link for solution:AsyncPostBackTrigger from another user control

Please check out these linka for more information:

Trigger PostBack to an UpdatePanel from a separate UserControl?

Can I specify a UserControl custom event as a Trigger for update panel on Parent page?

Bubble Event from UserControl

Best Regards

Need help adding item from a gridview to a Reorderlist programmically

I have a GridView which I programmically bound to a DataTable.

I also have a ReOrderlist which I've done the same.

I'm trying to have the user click "Add" on the gridview and it adds that row to the Reorderlist.

How can I do I this?


I was trying to pull back out the datasource fom the reorderlist and then add a datarow somehow and then send it back. But I get an object error on that, still working it out.


I'd rather somehow use the .Items.Add(xxx) method, but I don't know how to properly populate it. It wants a RorderListItem, fine, but the ReorderListItem wants a DataItem and I don't know where to get that.

Pretty confused.


Ok I was able to figure it out, I had to reload my datasource on post back before trying it out.

I'd rather do it using Me.QualificationReorderList.Items.Add() somehow, but instead, I pull back the datasource, add a row to it and then re-bind it.

1If e.CommandName.Equals("Add")Then2 Call LoadReorderListItems()34Dim TempReorderListDataTableAs New Data.DataTable5 TempReorderListDataTable =Me.QualificationReorderList.DataSource67Dim TempDataRowAs Data.DataRow89 TempDataRow = TempReorderListDataTable.NewRow1011 TempDataRow.Item("CERTIFICATION_ID") = 123412 TempDataRow.Item("CERTIFICATION_TITLE") ="12"13 TempDataRow.Item("DISPLAY_ORDER") = 01415 TempReorderListDataTable.Rows.Add(TempDataRow)1617Me.QualificationReorderList.DataSource = TempReorderListDataTable18Me.QualificationReorderList.DataBind()19End If

Wednesday, March 21, 2012

Need help designing a drag-drop resulting in a formatted output to the user

Hi

I have a request from a customer regarding a drag-drop-edit feature.

This is the idea:

An editor of a website must enter data to show for the web-site user. He has a fixed number of elements that can be used, most of which will be positioned the same place on every page, but a few can vary and some can be added multiple times (this is decided based on the database using relations). The editor would like to be able to have some sort of toolbox feature on his "Create journal", from this toolbox he can drag out elements, such as date, journal number, description, resume etc. When an item is dragged out on the "workspace" he can then enter the data that should go in that field, meaning the description box should be considerebly larger than the date box as example. When the editor has added all the elements to the journal he can save it and it is now visible on the website. The website visitors can now see the journal formatted the way the editor defined it.

I haven't worked alot with AJAX before, so I would like to hear if this is something AJAX can help me solve? If so links to usefull sites would be very welcomeSmile

Hi,

Thank you for your post!

Seehttp://forums.asp.net/t/1187961.aspx

Here is a simple demo to combine pictures at server side in C#:

using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;

namespace Enter_name
{
class GenerateImage
{
public struct favoriteImage
{
private string _imagePath;
private int _x;
private int _y;

public int x
{
get
{
return _x;
}
set
{
_x = value;
}
}

public int y
{
get
{
return _y;
}
set
{
_y = value;
}
}

public string imagePath
{
get
{
return _imagePath;
}
set
{
_imagePath = value;
}
}
}

[STAThread]
static void Main(string[] args)
{
string CurrentDirectory = System.Environment.CurrentDirectory;
string body_path = CurrentDirectory + "\\4.jpg";

favoriteImage[] FaImage = new favoriteImage[2];

FaImage[0].x = -3;
FaImage[0].y = 70;
FaImage[0].imagePath = CurrentDirectory + "\\1.jpg";

FaImage[1].x = 20;//65;
FaImage[1].y = -12;
FaImage[1].imagePath = CurrentDirectory + "\\2.jpg";

generateWinterMark(CurrentDirectory, body_path, FaImage);
}

/// <summary>
///
/// </summary>
/// <param name="savePath"></param>
/// <param name="body_path"></param>
/// <param name="favorite"></param>
/// <returns></returns>
private static string generateWinterMark(string savePath, string body_path, favoriteImage[] favorite)
{
//create a image object containing the photograph to watermark
Bitmap imgPhoto = new Bitmap(body_path);
int phWidth = imgPhoto.Width;
int phHeight = imgPhoto.Height;


string nowTime = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString();
nowTime += DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString();

string saveImagePath = savePath + "\\FA" + nowTime + ".jpg";

//create a Bitmap the Size of the original photograph
Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);
//setResolution
bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

//load the Bitmap into a Graphics object
Graphics grPhoto = Graphics.FromImage(bmPhoto);
//set the rendering quality for this Graphics object
grPhoto.SmoothingMode = SmoothingMode.AntiAlias;

for (int i = 0; i < favorite.Length; i++)
{
//Draws the photo Image object at original size to the graphics object.
grPhoto.DrawImage(
imgPhoto, // Photo Image object
new Rectangle(0, 0, phWidth, phHeight), // Rectangle structure
0, // x-coordinate of the portion of the source image to draw.
0, // y-coordinate of the portion of the source image to draw.
phWidth, // Width of the portion of the source image to draw.
phHeight, // Height of the portion of the source image to draw.
GraphicsUnit.Pixel); // Units of measure

//------------------
//Step #2 - Insert Property image,For example:hair,skirt,shoes etc.
//------------------
//create a image object containing the watermark
Bitmap imgWatermark = new Bitmap(favorite[i].imagePath);
int wmWidth = imgWatermark.Width;
int wmHeight = imgWatermark.Height;
imgWatermark.MakeTransparent(); //使默认的透明颜色对此 Bitmap 透明。


//Create a Bitmap based on the previously modified photograph Bitmap
Bitmap bmWatermark = new Bitmap(bmPhoto);

//bmWatermark.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
//Load this Bitmap into a new Graphic Object
Graphics grWatermark = Graphics.FromImage(bmWatermark);


int xPosOfWm = favorite[i].x;
int yPosOfWm = favorite[i].y;

//叠加
grWatermark.DrawImage(imgWatermark, new Rectangle(xPosOfWm, yPosOfWm, wmWidth, wmHeight), //Set the detination Position
0, // x-coordinate of the portion of the source image to draw.
0, // y-coordinate of the portion of the source image to draw.
wmWidth, // Watermark Width
wmHeight, // Watermark Height
GraphicsUnit.Pixel, // Unit of measurment
null); //ImageAttributes Object


//Replace the original photgraphs bitmap with the new Bitmap
imgPhoto = bmWatermark;//age(FromHbitmap(bmWatermark;

grWatermark.Dispose();
imgWatermark.Dispose();
}
bmPhoto.Dispose();
grPhoto.Dispose();

//save new image to file system.
imgPhoto.Save(saveImagePath, ImageFormat.Jpeg);
imgPhoto.Dispose();

return saveImagePath;
}
}
}

The demo show you that conbine 1.png and 2.png towhite.png.

Happy coding!

Need Help with Modal Popup!

Here's the deal...

I have a bound DetailsView (user control) that I have created custom command buttons for (add, edit, save, cancel).

Upon edit, I am storing the values for each field to hidden textboxes on the form. Upon save, I will need to run custom validation routine(s), as well as, compare old vs. new values (some changes will trigger back-end processes to kick off via SQL triggers and we want alert the user of this up front).

Once validation passes, if one or more of the values have changed that will cause execution of the triggers, I want to manually launch a popup [ modalpopup1.show() ] that lists the specific changes and asks the user to Confirm (ie., "Are they sure they want to Save?"). If so, the app will proceed with updating / saving the record and the SQL proc will go ahead and execute. If not, the update is cancelled and the detailsview goes back into read only mode.

Problem I am having is that the Modal wants me to specify a "TargetControlId" and I am not sure what that control should be. I tried making it the Save button, but doing so will cause the modal to appear immediately (ie., before the validations and old vs. new compare routine) executes. So I then tried creating a dummy button, but get the following error message: "The control 'btn_Dummy' already has a data item registered. Parameter name: control".

Can anyone help me on the proper way to code / implement this ?

Hi ,

The "TargetControlId" specifies the Control which will trigger the ModalPopup to Show .

What you can do is .. Once you come to know that certain changes have been made to the data , you can use the Client side methods of the ModalPopup to Show / Hide

Show and Hide ModalPopupExtender from JavaScript

Let me know if I missed anything


I tried this via example provided via thread ("Show Popup Dynamically via js") , but I really would like to popup the modal from another button's code behind (ie., after all my validations checks have been completed). Is there not a way to do this?

If not, I guess the only alternative would be to re-write the validation routines in js and call the popup from there??


From ServerSide , you have access to the ModalPopup's Show method using

ModalPopupExtender1.Show()

From Client side , use the method described in my previous reply.


Hi,

Still getting error message "data item already registered" when attempting to use ModalPopupExtender1.show().

Found thishttp://www.codeplex.com/AtlasControlToolkit/WorkItem/View.aspx?WorkItemId=7115 after doing more research on Google. It appears to be a bug.

Appreciate your trying to help. I've decide to manually hide / unhide my panels instead of the AJAX control until the above is resolved.

Thanks,

Annette

need help with page_load

Hi

I am new to development so i hope my question is not silly for you.I have developed a web page and there is user login part in an update panel.I check the session["status"] on page load and if it is true change the visibility of update panel to false and make the "welcome ..." lable visible. It works perfectly at first time but after page changing update panel became visible with the input textboxes again! In debug I have observed that the code do not enter the page load..While the screen that update panel and input textboxes are visible when I hit the (F5) to refresh the page update panel becomes invisible and "welcome ..." label becomes visible..So I thougth that it is a certain problem of Page_Load...

Is there any suggestion or solve method for this? Is my method for logging in is wrong for Ajax?

Thanks for concerning

Help needed please,it is urgent:(