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

Wednesday, March 28, 2012

programatically adding cascading dropdowns with the ability to add to the dropdownlist

I'll keep this as simple as possible, apologies in advance. Cascading dropdowns (CCD) are added to a page programatically. Each cascade dropdown (CCD) is added in a while lop based on the number of levels read in from a db table. beside each dropdown (CCD) is an add button, which when clicked pops up a modal window, allowing the user to via an update panel add to each the cascading dropdown (CCD) of choice. My problem is this I want the button beside the dropdown only to become enabled when the cascading dropdown is active/populated. So when I draw everything in theOnInit function I make the buttons beside the cascading dropdowns disabled. My Question is how do I enable them based on the (CCD) becoming active? and secondly am I doing this the correct way. Code below: Thanks in advance

While counter < SR.Item("Annello")

Lit =New Literal

If counter < 1Then

Lit.Text ="Category"

Else

Lit.Text ="Sub-Category"

EndIf

UPanel.ContentTemplateContainer.Controls.Add(Lit)

DDL =New DropDownList

With DDL

.ID ="DropDown" & counter

.Width = 250

.DataTextField ="CategoryName"

.DataValueField ="CID"

EndWith

UPanel.ContentTemplateContainer.Controls.Add(DDL)

Cascade =New AjaxControlToolkit.CascadingDropDown

With Cascade

.ID ="Cas" & counter

.TargetControlID = DDL.ID

If counter > 0Then

.ParentControlID ="DropDown" & counter - 1

.PromptText ="Please select a Sub-Category"

Else

.PromptText ="Please select a Category"

EndIf

.LoadingText ="Loading.."

.Category = counter

.ServiceMethod ="GetCategoriesPageMethod"

EndWith

UPanel.ContentTemplateContainer.Controls.Add(Cascade)

IB =New ButtonWith IB

.ID ="ADD" & counter

.Text ="add to.."

EndWith

UPanel.ContentTemplateContainer.Controls.Add(IB)

IB.Enabled =False

'''MODAL POPUP

NPanel =New Panel

With NPanel

.Style.Add(HtmlTextWriterStyle.Display,"none")

.Style.Add(HtmlTextWriterStyle.Height,"200px")

.Style.Add(HtmlTextWriterStyle.Width,"350px")

.Style.Add(HtmlTextWriterStyle.BackgroundColor,"#ffffff")

.Style.Add(HtmlTextWriterStyle.Padding,"10px")

.ID ="NPanel" & counter

EndWith

Lit =New Literal

Lit.Text ="Enter Your Category here "

NPanel.Controls.Add(Lit)

TBX =New TextBox

With TBX

.ID ="AddTBX" & counter

.Width =New System.Web.UI.WebControls.Unit(190)

EndWith

NPanel.Controls.Add(TBX)

IB =New ButtonWith IB

.ID ="OK" & counter

.Text ="OK"

'.Attributes.Add("onclick", "InsertCategory();")

EndWith

NPanel.Controls.Add(IB)

IB2 =New Button

With IB2

.ID ="Cancel" & counter

.Text ="Cancel"

EndWith

NPanel.Controls.Add(IB2)

UPanel.ContentTemplateContainer.Controls.Add(NPanel)

MP =New AjaxControlToolkit.ModalPopupExtender

With MP

.TargetControlID ="ADD" & counter

.PopupControlID ="NPanel" & counter

.OkControlID ="OK" & counter

.CancelControlID ="Cancel" & counter

.OnOkScript ="InsertNewCategory()"

.OnCancelScript ="alert('cancel');"

'.OnOkScript = "alert('OK');"

.DropShadow =False

.BackgroundCssClass ="ModalPopupBackground"

EndWith

UPanel.ContentTemplateContainer.Controls.Add(MP)

Hi

Try this,It works:

<td><asp:DropDownList ID="DropDown1" onchange="javascript:activeBtn(this)" runat="server" Width="170" /></td>

<script type='text/javascript'>
function activeBtn(ccd)
{
var strcounter = ccd.id.substring(ccd.id.indexOf("DropDown") + 8, ccd.length - 1);
var counter = parseInt(strcounter);
var theBtn = document.getElementById(ccd.id.replace("DropDown", "ADD").replace(strcounter, (counter + 1) + ""))
if(theBtn){
if(ccd.selectedIndex != 0)theBtn.disable = false;
else theBtn.disable = true;
}
}
</script>

You can add the onchange event handlers for your DropDownLists in code-behind by using this code:

DDL =New DropDownList

With DDL

.ID ="DropDown" & counter

.Width = 250

.DataTextField ="CategoryName"

.DataValueField ="CID"

.Attributes.Add("onchange", "javascript:activeBtn(this);")

EndWith

Best Regards


Gave that a go and couldn't get it to work. I see what your doing and I'm hitting the function and even if I hardcode the Button.ID to enable that one button it doesn't work, no errors but it just won't enable it... any ideas. Thanks in advance..


Hi

Sound odd,I have test it many times.I'm sure it works.

Would you please privide us with a whole demo?

Thanks


ThanksJin-Yu YinSmile


Firstly thanks for you help. It is strange that it doesn't work, the funny thing is if I change you function to the following it works, but I'd never have gotten there without your help. Again many thanks.

function activeBtn(ccd)

{

var strcounter = ccd.id.substring(ccd.id.indexOf("DropDown") + 8, ccd.length - 1);

var counter = parseInt(strcounter);

var theBtn = document.getElementById(ccd.id.replace("DropDown","ADD").replace(strcounter, (counter + 1) +""))

if(theBtn){

if(ccd.selectedIndex != 0)

{

if (theBtn.disabled) {theBtn.disabled =false;}else theBtn.disabled =true;

}

}

}


Hi

Glad to hear that it works now.I'm sorry for misunderstanding any logic of it.

Best Regards


Like I said mate, thanks ,u were 100% bang on. Appreciate the help.

Programmatic cascading dropdown repopulation

Greetings, all...

Time for yet another plaintive cry for help out to the Ajax community.

I've got a page with four cascading dropdown lists chained together. Everything is working fine.

Where my problem comes is when I add a new row into the database (via a web service) and now I want to call the parent dropdown list and repopulate it once I receive a success code from the ws. I want to be able to do this all via client-side, and I think (hope?) I'm close, but I just can't seem to get the ddl to update its options.

Here's the code so far. As you can see, I've been trying to tackle this two ways...using a $find().populate on the dropdownlist, and, alternatively, calling the web service directly. The web service call does, in fact, retrieve all the levels, including the newly added level, but I'm not understanding how to "bind" the results to the dropdown.

function AddNewLevel()
{
var txt = document.getElementById('<%= txtAddLevel.ClientID %>')
retVal = QuestionManagerWS.AddNewLevel(txt.value, OnAddLevelOk, OnTimeout, OnError);
return(true);
}

function OnAddLevelOk(result)
{
alert(result);
// This doesn't appear to do anything...it never calls the ws, etc.
$find('<%= ddlLevel.ClientID %>').populate;

// This calls the web service and gets the correct values...but how does it bind to the ddl?
//document.getElementById('<%= ddlLevel.ClientID %>');
//QuestionManagerWS.GetLevels("","Level");
}

Anyway, I would really appreciate any help that may be out there. I've looked at the stuff in the 'manual' folder of the ToolkitTests (there's usually a gem or two in there) but nothing gives any hint on how to get this to work.

Thanks in advance,

Ric

Does anyone have any ideas on this one? I'm still stumped and need some help.

I figured out a resolution to the problem.

I've blogged about it onmy site and in a few days will be putting together an article as an example to my solution.

Programmatic client side initialization of HoverMenuPopup

I am trying to link a HoverMenuPopup to anchor tags on a page programmatically and I would like to implement something similar to the FAQ #13:
http://forums.asp.net/t/992919.aspx

This code is outdated now, and does not work.

How would it be written for the released version of the AJAX Control Toolkit?

Thank you,

Jeff

Hi Jeff,

Here is a sample made according to your requirements, please try it.

<%@. Page Language="C#" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" ><head id="Head1" runat="server"> <title>Untitled Page</title></head><body> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager> <div> <input type="button" onclick="addHoverMenu();" value="Add Hovermenu to HyperLink" /><br /> <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="http://www.msdn.com">HyperLink</asp:HyperLink> <asp:Panel ID="Panel1" runat="server" Height="50px" Width="125px"> Item1<br /> Item2<br /> Item3<br /> Item4<br /> </asp:Panel> <script type="text/javascript"> function addHoverMenu() { $create(AjaxControlToolkit.HoverMenuBehavior, {"id":"Repeater1_ctl10_HoverMenuExtender1","popupElement":$get("<%= Panel1.ClientID%>")}, null, null, $get("<%= HyperLink1.ClientID%>")); } </script><div style="display:none;" >Controls in this div are used to import necessary javascripts. <asp:LinkButton ID="LinkButton1" runat="server">LinkButton</asp:LinkButton> <asp:Panel ID="Panel2" runat="server" Height="50px" Width="125px"> </asp:Panel> <ajaxToolkit:HoverMenuExtender ID="HoverMenuExtender1" PopupControlID="Panel2" runat="server" TargetControlID="LinkButton1"> </ajaxToolkit:HoverMenuExtender> </div> </div> </form></body></html>

That is what I was looking for Raymond. Now I will need to look into setting the popup location, timeout, etc.

Thank you,

Jeff


Raymond,

I've run into a bit of a snag with the popup. What I want to do is link a number of anchor tags to a single popup instance. When I use the logic of attaching behaviors to multiple anchors, certain events attached to the single popup cause the popup to jump between the anchor tags when I mouse over the popup (after hovering over a second anchor associated with the same popup).

What would you suggest I change in the below code to address this:

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

<%@. Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
Namespace="System.Web.UI" TagPrefix="asp" %>
<%@. Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Hover Sample</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>

<script type="text/javascript">
function hover(element)
{
var behaviorName = "HoverMenuExtender_" + element.uniqueID;
var behavior = $find(behaviorName);
var popupElement = $get("<%= pnlHoverPopup.ClientID%>");

if (behavior == null)
{
behavior = $create(AjaxControlToolkit.HoverMenuBehavior, {"id":behaviorName, "popupElement":popupElement, PopDelay:750, OffsetX:-200, OffsetY:16}, null, null, element);
behavior.set_PopupPosition(AjaxControlToolkit.HoverMenuPopupPosition.Bottom);
}
}
</script>

<div>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean nisl justo, sagittis
id, tincidunt nec, euismod ac, turpis. Proin ante. Sed venenatis libero ac nisi.
Nunc varius ultrices velit. Donec vestibulum interdum ligula. Class aptent taciti
sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Nulla facilisi.
Nunc vel ligula. In <a href="http://links.10026.com/?link=http://forums.asp.net/p/1167961/1956419.aspx#1956419#" onmouseover="return hover(this);">Internet</a> nisi
eget turpis. Nunc diam. Etiam congue ipsum. Proin vitae mauris et risus ultrices
vestibulum. Phasellus laoreet lectus quis augue. Vestibulum accumsan. Curabitur
sit amet eros eu justo rhoncus eleifend. Donec semper pharetra nibh. Pellentesque
habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.
Pellentesque habitant morbi tristique senectus et netus et <a href="http://links.10026.com/?link=http://forums.asp.net/p/1167961/1956419.aspx#1956419#" onmouseover="return hover(this);">
Internet</a> fames ac turpis.
</div>
<asp:Panel ID="pnlHoverPopup" runat="server" Style="visibility:hidden;background-color:#ccccff;width:300px; padding:10px;color:#000000;">
<h3>
Internet</h3>
A series of interconnected local, regional, national and international networks,
linked using the Internet Protocol. The Internet is accessible via telephony wires,
HFC networks and by satellite.
</asp:Panel>
<div style="display: none;">
Controls in this div are used to import necessary javascripts.
<asp:LinkButton ID="LinkButton1" runat="server">LinkButton</asp:LinkButton>
<asp:Panel ID="Panel2" runat="server" Height="50px" Width="125px">
</asp:Panel>
<ajaxToolkit:HoverMenuExtender ID="HoverMenuExtender1" PopupControlID="Panel2" runat="server"
TargetControlID="LinkButton1">
</ajaxToolkit:HoverMenuExtender>
</div>
</form>
</body>
</html>

Thank you,

Jeff

Programmatically adding a ConfirmButtonExtender

Hi,

I cannot get my ConfirmButtonExtender to work when I add it from the code behind.

A javascript page error occurs the page loads:

Line: 2829
Char:23
Error: Sys.ArgumentException: Value must not be null for Controls and Behaviors.
Parameter name: element
Code:0

---------------

Here is the code:

-- .asp snippet----

 <asp:ScriptManager ID="ScriptMan1" runat="server"> </asp:ScriptManager> <asp:Panel ID="Panel1" runat="server"> </asp:Panel> 

---.asp.cs snippet----

protected void Page_Load(object sender, EventArgs e) { Button button =new Button(); button.Text ="Click Me"; Panel1.Controls.Add(button); AjaxControlToolkit.ConfirmButtonExtender confirmDeleteExt =new AjaxControlToolkit.ConfirmButtonExtender(); confirmDeleteExt.TargetControlID = button.UniqueID; confirmDeleteExt.ConfirmText ="Are you sure?"; Panel1.Controls.Add(confirmDeleteExt); }

----------

It's nothing special, but what am I missing?!

I am dynamically building the page, so beginning with the button on the page is not an option (which works no problem).

Thanks!

Your code works fine on my computer.


OK,

Thanks for your reply, kipo, looking at it again it seems that the error only seems to occur when using a masterpage.

Does it still work for you if you put all of it into a masterpage?


I've tried to put your code in page which is using MasterPage and it doesn't work, so you were right - error is occuring only with MasterPage. But, you can achieve it with this code:

Button button = new Button();
button.Text = "Click Me";
button.ID = "button1";
Panel1.Controls.Add(button);

AjaxControlToolkit.ConfirmButtonExtender confirmDeleteExt = new AjaxControlToolkit.ConfirmButtonExtender();
confirmDeleteExt.TargetControlID = "button1";
confirmDeleteExt.ConfirmText = "Are you sure?";
Panel1.Controls.Add(confirmDeleteExt);


Excellent!Big Smile

Thanks a lot for your help!

I thought this problem was related to IDs, but is this a bug or is this by design?

Programmatically adding ASP.net User Control to Partial Page Update / UpdatePanel

Hi All, I got a real doozy here. I have read hundreds upon hundreds offorum posts and found numerous others who have replicated this problem,but have yet to find a solution. Through testing I have been able tofind the cause of the problem, and will describe it here firsttextually and then through a code example.

Thepurpose of what I am trying to do is to create a postback-free webapplication through the use of ASP.net AJAX UpdatePanels and UserControls. When programmatically adding a User Control to a web pagethrough a normal postback everything works fine. All the controlswithin the user control are registered properly in the page and anyupdate panels included in the user control also work properly. HOWEVER,if instead of using a full postback you use an UpdatePanel and apartial page update of the UpdatePanel the controls do not getregistered with the page and events from them do not fire (forinstance, a button click event never hits the event breakpoint).

Becausethe very same user control works fine if loaded in a full postback ordynamically added from a namespace works fine, I can be relatively surethat it only is trouble when loading via a partial page update into anUpdatePanel. I load the control via the LoadConrol method and then addit to the page via a PlaceHolder control. Theoretically, adding theUser Control to the PlaceHolder should register itself and it'scontrols and events with the page, but it does not.

Thefollowing code sample is a UpdatePanel-free page using a user controlthat works, later I will show the same code with an UpdatePanel thatdoes not.

I think I need to figure out how to register thecontrols and their events with the page without going through a fullpage postback. Any suggestions??

This example works as expected:
Default.aspx:

1<%@dotnet.itags.org. Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
2
3<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4<html xmlns="http://www.w3.org/1999/xhtml">
5<head runat="server">
6 <title>Untitled Page</title>
7</head>
8<body>
9 <form id="form1" runat="server">
10 <div>
11 <asp:PlaceHolder ID="UCPlaceHolder" runat="server"></asp:PlaceHolder>
12 </div>
13 </form>
14</body>
15</html>

Default.aspx.cs:
1using System;
2using System.Data;
3using System.Configuration;
4using System.Web;
5using System.Web.Security;
6using System.Web.UI;
7using System.Web.UI.WebControls;
8using System.Web.UI.WebControls.WebParts;
9using System.Web.UI.HtmlControls;
10
11public partialclass _Default : System.Web.UI.Page
12{
13protected void Page_Load(object sender, EventArgs e)
14 {
15 Control ctl = LoadControl("~/UserControlDemo.ascx");
16 ctl.ID ="UC1";
17this.UCPlaceHolder.Controls.Add(ctl);
18 }
19}

UserControlDemo.ascx:
1<%@dotnet.itags.org. Control Language="C#" AutoEventWireup="true" CodeFile="UserControlDemo.ascx.cs" Inherits="UserControlDemo" %>
2<asp:Button ID="Button1" runat="server" Text="Display from UC" OnClick="Button1_Click" /> <br />
3<br />
4<asp:Label ID="Content" runat="server" Text="Content"></asp:Label>

UserControlDemo.ascx.cs:
1using System;
2using System.Data;
3using System.Configuration;
4using System.Collections;
5using System.Web;
6using System.Web.Security;
7using System.Web.UI;
8using System.Web.UI.WebControls;
9using System.Web.UI.WebControls.WebParts;
10using System.Web.UI.HtmlControls;
11
12public partialclass UserControlDemo : System.Web.UI.UserControl
13{
14protected void Page_Load(object sender, EventArgs e)
15 {
16 }
17protected void Button1_Click(object sender, EventArgs e)
18 {
19 Content.Text ="Content Changed.";
20 }
21}

Now,consider this variation, where instead of loading the control in thePageLoad event, you do so programmatically via a button Click event.This does not work as it cause a full postback which refreshes theplaceholder. Viewstate does not seem to be working in this case. (usesthe same user control as the previous example)

Default.aspx:

1<%@dotnet.itags.org. Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
2
3<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4<html xmlns="http://www.w3.org/1999/xhtml">
5<head runat="server">
6 <title>Untitled Page</title>
7</head>
8<body>
9 <form id="form1" runat="server">
10 <div>
11 <asp:Button ID="Button1" runat="server" Text="Load User Control" OnClick="Button1_Click" />
12 <br />
13 <br />
14 <asp:PlaceHolder ID="UCPlaceHolder" runat="server"></asp:PlaceHolder>
15 </div>
16 </form>
17</body>
18</html>

Default.aspx.cs:
1using System;
2using System.Data;
3using System.Configuration;
4using System.Web;
5using System.Web.Security;
6using System.Web.UI;
7using System.Web.UI.WebControls;
8using System.Web.UI.WebControls.WebParts;
9using System.Web.UI.HtmlControls;
10
11public partialclass _Default : System.Web.UI.Page
12{
13protected void Page_Load(object sender, EventArgs e)
14 {
15 }
16protected void Button1_Click(object sender, EventArgs e)
17 {
18 Control ctl = LoadControl("~/UserControlDemo.ascx");
19 ctl.ID ="UC1";
20this.UCPlaceHolder.Controls.Add(ctl);
21 }
22}

Tosolve this postback problem, one would naturally want to use anUpdatePanel, like the following example. However this does not work asthe controls do not seem to get registered with the page, and furthernesting of user controls in UpdatePanels (to create a postback freeapp) are no better.

Default2.aspx:

1<%@dotnet.itags.org. Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
2
3<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4
5<html xmlns="http://www.w3.org/1999/xhtml" >
6<head runat="server">
7 <title>Untitled Page</title>
8</head>
9<body>
10 <form id="form1" runat="server">
11 <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true"></asp:ScriptManager>
12 <div>
13 <asp:UpdatePanel ID="UpdatePanel2" runat="server">
14 <ContentTemplate>
15 <asp:Button ID="Button1" runat="server" Text="Load User Control into UpdatePanel" OnClick="Button1_Click" />
16 </ContentTemplate>
17 </asp:UpdatePanel>
18 <br />
19 <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
20 <ContentTemplate>
21 <asp:PlaceHolder ID="ContentPlaceHolder" runat="server"></asp:PlaceHolder>
22 </ContentTemplate>
23 <Triggers>
24 <asp:AsyncPostBackTrigger ControlID="Button1" />
25 </Triggers>
26 </asp:UpdatePanel>
27 </div>
28 </form>
29</body>
30</html>

Default2.aspx.cs:
1using System;
2using System.Data;
3using System.Configuration;
4using System.Collections;
5using System.Web;
6using System.Web.Security;
7using System.Web.UI;
8using System.Web.UI.WebControls;
9using System.Web.UI.WebControls.WebParts;
10using System.Web.UI.HtmlControls;
11
12public partialclass Default2 : System.Web.UI.Page
13{
14protected void Page_Load(object sender, EventArgs e)
15 {
16
17 }
18protected void Button1_Click(object sender, EventArgs e)
19 {
20 Control ctl = LoadControl("~/UserControlDemo.ascx");//loads into the page
21 ctl.ID ="UC1";
22this.ContentPlaceHolder.Controls.Add(ctl);//adds to page control tree (or at least it should)
23 }
24}

I knowI can use the "visible" property of my controls to toggle them on andoff a page to create a flicker free experience, however, my applicationis a database intensive app and I don't want the page running queriesagainst the database unless I'm absolutely sure the user wants them.Rendering a 10 forms and keeping them hidden isn't a big deal, butrunning 10 queries that the user never wants to see is, otherwise I'dstick to that method, its works perfectly. Any suggestions? Or requestsfor clarification? Any help you can provide is muchappreciated...thanks, Chris.

My suggestion is to not use an updatepanel for this. Google for ScottGu's blog on templating tricks; you can use a service to grab an ascx, feed it a datasource to populate the data then send the results to the page. use javascript to insert those results into the page DOM where needed, and code all your functionality in js or web methods of one form or another. It's a much cleaner / lower overhead way to do what you're trying to do anyway.


Hi Paul, I took a look at ScottGu blog, I believe this is the article you were referencing: http://weblogs.asp.net/scottgu/archive/2006/10/22/Tip_2F00_Trick_3A00_-Cool-UI-Templating-Technique-to-use-with-ASP.NET-AJAX-for-non_2D00_UpdatePanel-scenarios.aspx

Unfortunately this is not the solution I am looking for. By using this method I lose the main benefits of ASP.net: managed code, event based triggers, and the rest of the integrated features. I believe this method will cause the same problem, whatever I load into the page, the page won't be aware of it and no events will fire.

For now I am going to have to use postbacks, and I'll used the update panels for keeping things like sorting gridviews postback-less.

Thanks for the suggestion though!


I am having exactly the same problem

Can someone please help?

In similar situations before, I have used javascript and other hacks, but I feel reluctant to try to do it again. If we have a framework that can be used and can make work simpler, then It makes sense.

However, these kind of problems are frustrating, and I don't know what is the resolution. I am sure people mus thave encountered this before.

Can someone help?


This is more a dynamic controls problem than an AJAX problem.

When you dynamically add a control, you have to add it EVERY request. By moving it from PageLoad to Button_Click, you've stopped creating the control every request. You only create it if the button is pressed. That is why the events won't fire when you use controls within the user control -- because on the postback, the control doesn't even exist! The postback data is for a control that isn't in the control tree, because you didn't add it, because the event that adds it isn't firing again.

The technique to solve this is to utilize viewstate to remember that the control has been added, so that you can add it from the LoadViewState method. In your click handler, call a new method - LoadUserControl(). Define LoadUserControl to create and add the control, and to set a viewstate key, ViewState["LoadUserControl"] = true. Then override LoadViewState, and after calling base.LoadViewState, look for that viewstate key. If its true, call LoadUserControl().

New problem... Now its possible it will be added twice -- if you click the same button a 2nd time, LoadViewState will call it, and so will your button click handler. So add code to your button click handler to avoid creating it if its already loaded -- just check for the viewstate key.


Infinities...This is very interesting, thank you for your response! Unfortunately you lose me when you talk about overriding the LoadViewState. How would you modify the following code to accomplish what you are saying?

protected void Button_Click(object sender, EventArgs e)
{
Control ctl = LoadControl("~/userControl.ascx");
this.Panel1.Controls.Add(ctl);
}
Thanks!

Ok, that sounds promising. But, I don't think the situation would work still.

I have a gridView. In every row of a gridview, one of the cells contains a nested update panel. When the user clicks on a particular row, a user control dynamically gets added to the nested update panel. This works fine.

When I click on a particular button INSIDE this user control then the postback disappears, no events are triggered and nothing happens. The fact that the control probably does not exist makes sense because it justifies what happens, as in no events are fired.

However now this user control has values and data inside it, so when you are saying to load that control again, what happens to the value and the data, it looks like that data is lost. Is that not right?

Basically, in my situation AJAX cannot help. In the first place my user control should already have a viewstate in order to persist the value of data and state of the elements inside the user control. Since its viewstate is not stored, the "re-adding" will simply not work at all.


gsinha25:

However now this user control has values and data inside it, so when you are saying to load that control again, what happens to the value and the data, it looks like that data is lost. Is that not right?

No that is not right. The fact you are loading it again doesn't mean its data is lost. All controls are reloaded every request, even the statically declared ones. ViewState maintains itself through the framework, but it only maintains the data in the control, not the control itself.

gsinha25:

Basically, in my situation AJAX cannot help.

You would have the same problem if you were not using ajax. What you'd see is that the loaded user control would disappear after you click a button in it.

gsinha25:

In the first place my user control should already have a viewstate in order to persist the value of data and state of the elements inside the user control. Since its viewstate is not stored, the "re-adding" will simply not work at all.

ViewState is maintained for the control. All you have to do is make sure it exists every request. It will work, trust me.


I'm sure the formatting of this is going to be off, but here's the basic idea.

protected void Button_Click(object sender, EventArgs e)
{
LoadUserControl();
}
private void LoadUserControl()
{
Control ctl = LoadControl("~/userControl.ascx");
this.Panel1.Controls.Clear();
this.Panel1.Controls.Add(ctl);

 ViewState["Loaded"] = true;

}
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);

 if (ViewState["Loaded"] != null)
LoadUserControl();
 }


Hi Infinities,

This is starting to make sense. I believe what you are talking about will work for my problem - in fact I often assumed it had something to do with the viewstate, however my knowledge and experience with it is limited. (I am new to C# and ASP.net, coming over from ColdFusion.) I am still a little confused on the the LoadViewState override. As I understand it, this event fires after the Init event in the lifecyle, and it's goal is to reload the user control if it has been added to the page. One question that pops up here, and may be what gsinha was referencing, does chages to the control also progress if it is reloading the control every time? For instance, if the user control is a gridview populated from a database and I have sorted and/or filtered it, would these sorts and filters be passed along as well?

Another question, when you assign the view state key in "ViewState[" "] = true" does it matter which key you use? And a final question, where is the savedState object coming from in the LoadViewState override?

Thanks again for your help!

P.S. I read your writeup at your website on the viewstate, I think i'll need to read it three or four more times before I can make sense of it all but amazing stuff, I love the attention to detail!


ChrisCicc:

As I understand it, this event fires after the Init event in the lifecyle, and it's goal is to reload the user control if it has been added to the page.

The general role of LoadViewState is to deserialize the control's share of the page's entire viewstate payload. Think of viewstate as just a bunch of data -- data which is associated with each control on the page. On a postback, that data is available to the control that owns it again, if it's still around that is. The role of the code I gave you is to recreate the control if it was remembered previously that it had been created.

ChrisCicc:

One question that pops up here, and may be what gsinha was referencing, does chages to the control also progress if it is reloading the control every time? For instance, if the user control is a gridview populated from a database and I have sorted and/or filtered it, would these sorts and filters be passed along as well?

Yes -- because what you have to understand is that all controls are reloaded every request. In fact, the page is completely reconstructed from the ground up every request. Remember request/response mechanism of the web is essentially a stateless process. ASP.NET and other frameworks create the feeling of statefulness through tricks like ViewState and Session state. ViewState is persisted across posts -- the controls are not. You create the control tree for the page by either statically declaring it with asp.net markup, or by dynamically creating the controls yourself. But either way, the controls start completely fresh and new every request. ViewState is then deserialized and injected into the controls, restoring them to the state they were on the last request.

ChrisCicc:

Another question, when you assign the view state key in "ViewState[" "] = true" does it matter which key you use?

No -- the idea is just to remember the fact that the control was loaded. Each control's viewstate is scoped to it, so there's no risk of using a key thats already in use by some other control.

ChrisCicc:

And a final question, where is the savedState object coming from in the LoadViewState override?

That is the deserialized viewstate associated with that specific control. The base implementation uses it to repopulate the keys stored in the ViewState statebag.


ChrisCicc:

P.S. I read your writeup at your website on the viewstate, I think i'll need to read it three or four more times before I can make sense of it all but amazing stuff, I love the attention to detail!

Thanks for reading :) I know it's quite long... but hopefully worth it.


It works!! Thanks a bundle! This solved the most important problem I had, which was loading the user control on to the page via an Update Panel. It does however bring up a few further questions that I was hoping you could help with!

First, how do I modify your code so that I can have multiple buttons load different UCs each while still using the LoadViewState override? The following code is my best attempt at it:

Instead of using the click event to call the LoadUserControl function, I did this:

  
protected void LinkButton_Click(object sender, EventArgs e)
{
MainBodyPanel.Controls.Clear();
Control ctl = LoadControl("UserControl.ascx");
MainBodyPanel.Controls.Add(ctl);

ViewState["Loaded"] =true;
}

And then in the override I did as you suggested, only added an addtional If statement for each button and control,
and sent it back to the click event function instead of the LoadUserControl so that each control could have its
own viewstate key.
While I can add new controls to the page, I cannot see them again once another control calls the .clear()
function an all that is left is the viewstate which then throws an error as it doesn't see the same control tree.
Is there a better way?
 
The second problem I have is I cannot get different user controls to communicate with each other. This is
apparent in two places. The first is I have a user control with a set of links. it is these links that call the
other user controls into the update panel dynamically. If I add the UserControl dynamically before the page
loads, the links can't see the container panel on the page. I tried using this.findControl("...").Controls.Add()
but that didn't work. So for now I have the links hard coded into the page instead being their own user control,
but it's really too complex to keep doing it that way, and it limits my nesting options.
Thanks again for any help u can provide! 
 

Ok... help me understand :) You have a bunch of links, which when one is clicked, you want to dynamically load a user control into a particular spot. Is that 'spot' different for each link? If you click on one link and then another are there supposed to now be 2 controls on the page or does the 2nd one replace the first?

I'll assume you want only 1 control at a time.

What you described sounds like it should work. I personally wouldn't explicitly call the event handler -- thats usually a bad idea. It won't cause any problems if you know what you're doing but its better design to have a 3rd method that they both call, which gives each method a clear distinct purpose (its generally bad if you have to think... who called this method?).

One think you should definitely do is give the User Control you load a particular ID. Make the ID based on something that will (1) be exactly the same every time and (2) be different for different user controls. So for example, clicking on Link1 might load UC1.ascx with ID "uc1", and clicking Link2 might load UC2.ascx with ID "uc2". The reason for this is.. well, when you dont specify an ID, any control that requires one (textboxes for example) will use an autogenerated one. But if you load controls differently on a postback than you did on the first request, the IDs wont necessarily be the same, causing problems. Assigning an ID avoids that. You shouldn't have been getting the exception you mentioned... try what I said and let me know. If you still get it, show me some code...

About your user control communication problem... I'm not following 100%. Where and when exactly are you calling FindControl, and what control are you trying to find? With controls whenever you find yourself trying to get two of them to talk directly to each other... well its usually a sign that you could improve your design a bit. The control should be self sufficient, it shouldn't be broken because something else on the page isnt just so. Rather than have the control talk to the other control, you can have it raise an event. The page then listens for the event and decides what to do with it (something which the original control doesn't much care about), which may be to push something into another control on the page (the origin of which that control doesn't much care about). Much less coupled that way.


"I'll assume you want only 1 control at a time." correct assumption. there is a panel placeholder that the controls get swapped in and out of.

I tried adding the ID as you suggested but the exception still came up. Here is the code as it currently stands:

1protected void ViewCustomerListLinkButton_Click(object sender, EventArgs e)2 {3 MainBodyPanel.Controls.Clear();4 Control ctl = LoadControl("~/UserControls/CustomersControls/CustomerList.ascx");5 ctl.ID ="CustList";6 MainBodyPanel.Controls.Add(ctl);78 ViewState["CustList"] =true;9 }1011protected void AddCustomerLinkButton_Click(object sender, EventArgs e)12 {13 MainBodyPanel.Controls.Clear();14 Control ctl = LoadControl("~/UserControls/CustomersControls/CustomerAdd.ascx");15 ctl.ID ="CustAdd";16 MainBodyPanel.Controls.Add(ctl);1718 ViewState["CustAdd"] =true;19 }2021protected override void LoadViewState(object savedState)22 {23base.LoadViewState(savedState);2425if (ViewState["CustList"] !=null)26 ViewCustomerListLinkButton_Click(null,null);2728if (ViewState["CustAdd"] !=null)29 ViewCustomerListLinkButton_Click(null,null);3031 }

The exception is thrown because when I click on a second link, it Clears the MainBodyPanel control list, and the viewstate is looking for the control list that includes the now removed control. I tried various ways I could think of to remove the viewstate but to no avail...

"What you described sounds like it should work. I personally wouldn'texplicitly call the event handler -- thats usually a bad idea. It won'tcause any problems if you know what you're doing but its better designto have a 3rd method that they both call, which gives each method aclear distinct purpose (its generally bad if you have to think... whocalled this method?)."

I couldn't figure out a way to do this. I was having each click event pass the url via the function call LoadUserControl("~/control.ascx") but I couldn't figure out how to have the loadviewstate override pass the url back when needed, so I did it as you see above.

About the communication problem, in more detail, the problem is actually with the code above. Right now that is in my pages code behind, if i make those links into a user control, and then add the control to the page with those functions in the controls code behind, it cannot see the container panel (which in this case is the MainBodyPanel). I tried using the find control method but it still couldn't see it. With the links and event handlers hard coded it works fine.

Thanks!


With this code, once you click on one of the buttons, that control will always be loaded. When you click on one button you need to 'clear' the viewstate key of the other, otherwise you'll be trying to load both controls all the time. Pretty sure that is why you are getting the error, too. Easier if you just use the same key with a different value.

About the event handler thing...

protected void Link1_Handler(object sender, EventArgs args) { Foo(); }
private void Foo() { /* load Foo, set ViewState["Loaded"] = 1 */ };

protected void Link2_Handler(object sender, EventArgs args) { Bar(); }
private void Bar() { /* load Bar, set ViewState["Loaded"] = 2 */ };

protected override void LoadViewState(object savedState) {
base.LoadViewState(savedState);

if(ViewState["Loaded"] == 1) {
Foo();
}
else if(ViewState["Loaded"] == 2) {
Bar();
}
}

You might be tempted to store the path to the actual UserControl in ViewState, that way you can just LoadControl(ViewState["Loaded"]) ... but, don't :) Treat ViewState like user input. Don't trust it. If you did it that way, the user could maniuplate viewstate in such a way that they could cause any user control in your site to load, rather than be restricted to the two you want.

Ok... so I'm still confused about your links problem. You have each link as a user control, and when clicked you want them to load their content into the parent? Controls should not modify their parent's controls. It would be better like I said, to have an event raised by the control. The page, which contains all these link controls, just hooks that event on each control and then loads the control into the appropriate place. Your FindControl probably isn't working because FindControl only finds controls within the current naming container. User controls are naming containers. So when you say, this.FindControl("foo") from within a UserControl, you're only looking for a control named "foo" WITHIN the user control, not higher. To go higher you have to call FindControl on a control thats higher. But you still have to be careful with naming containers. You could start at the page level with this.Page.FindControl("foo"), but that will only find controls named "foo" that are children of page or children of non-naming containers in page. Imagine if you had a user control that contained control with ID "foo", and then you put 5 of them on the page. Which would you expect Page.FindControl("foo") to find? Its ambiguous -- thats why it won't find ANY. Each Foo is within a naming container, so their actual IDs are "uc1$foo", "uc2$foo", etc (where uc1=id of user control 1). If you know for sure the control will be in a particular place (for you it sounds like in a master page), then go ahead and hard code that ID... but be warned, its a fragile way to do it. Another approach is to have your Page expose a "MasterContainer" property of type Control. The user controls can then just say ((MyPageType)this.Page).MasterContainer.Controls.Add(), and it will work so long as the control is on a page that inherits from "MyPage" (which, all of your pages could inherit from).Ad infinitum... lots of different ways to deal with it.

Programmatically Adding Controls and Events

Hi, I am trying to add several link buttons to a page programmatically with the following code:

int i;
int i;
for (i = 0; i < 60; i++)
{
LinkButton lnk = new LinkButton();
lnk.ID = "region" + i;
lnk.CssClass = "mystyle";
lnk.Click += new System.EventHandler(lnk_Click);

addContent.Controls.Add(lnk);

}


which adds them perfectly, however I also want to add an event handler to them all (the same event handler) which I had hoped to achieve by adding the ' lnk.Click += new System.EventHandler(lnk_Click);'
however when the link buttons are now clicked the page freezes, any suggestions?

All that is assigned on the onclick event is a write out to a label within an ajax.net update panel.

Any help would be appreciated, cheers Jon

I set this up in my dev environment and wa sunabel to duplictae it. Can you post more of your code... the ASP and the code behind to give us a better idea of whats going on.

I got the code working - for some reason the fact that the linkbuttons were placed inside a updatepanel and that the 'childrenastriggers' set to true seems to cause the slow down.

I think i know the problem but i am not sure how to solve it!

basically my onload function generates around 1500 linkbuttons in tiny squares within an update panel, each assigned a unique ID.

onclick of each button it posts its unique number to a textbox (temporarily so i can see if it is doing something) it takes around 60 seconds to do this when the 'childrenastriggers' is set to true.

When this is not set to true it performs it instantly, which is fine, however what I am trying to achieve that on click of the linkbutton it puts the number in the box, and changes the css of the linkbutton, updates so the user can see it has changed.

However the update panel is refreshing the generation of 1500 link buttons - which is causing the slow down.

Without the update panel refreshing, and if i cause a full postback the change is instant.

Any ideas on how to get around this but still achieve something similar.


Try and place your button generation code in the Page_Init event.


worked a treat, thank you!

Programmatically adding multi DragPanelExtenders?

Hi;

First of all what I need is to have more then one dragable panels inside my page. DragAndDrop em, record their locations to the DB

I'm using this script that I found in asp.net forum to find the location:

<scripttype="text/javascript">
Sys.Application.add_load(dragSetup);
function dragSetup() {
var dragPanel = $find('dragPanelBehavior1');
dragPanel.add_propertyChanged(locationUpdatedHandler);// the handler would get the name of the property from the event args and if it is 'location' then do the right thing.
returnfalse; }

function locationUpdatedHandler(sender, eventargs) {
if(eventargs.get_propertyName() =='location') {
var dragPanel = $find('dragPanelBehavior1');
var label = $get('dragPanelLocation');
var loc = dragPanel.get_location()
label.innerHTML = loc;}
}
</script>

However because of this script I have in the webusercontrol whenever I add my second webusercontrol it returns an error because they both aims the same panel's dragPanelBehavior1.

I couldn't solve this problem, any help would be preciated.

Again what I actually need is more then one dragable panels containig a webusercontrol and that I can find the location.

Thanks in advance

Hi Kaan,

First, DragPanelExtender's BehavirID should be uniquej though they are in different WebUserControls which are located in the same page.

Secondly, in your situation, I think you should remove out the Sys.Application.add_load(dragSetup) and its related functions from WebUserControls to the page.

To get or set the Panel's location , we can also use

//get

var el = $find('DragPanelBID').get_element();
var newLocation = $common.getLocation(el);

//set

var finalLocation = new Sys.UI.Point(x,y);
$find('DragPanelBID').set_location(finalLocation);

Hope this help.

Best regards,

Jonathan

Monday, March 26, 2012

Programmatically setting EnablePartialRendering to false from master page

Hi,

I have a master page which has its content area wrapped inside an updatepanel. To facilitate debugging, I'ld like to "disable" the updatepanel when the request URL contains ?debug=true.

I understood that to disable the updatepanel, setting EnablePartialRendering to false should do the trick. This can only be done from PreInit.

The problem I'm facing now is that:

The master page doesn't have an OnPreInit method to overrideWhen I override the OnPreInit in the content page, there's no ScriptManager available (via ScriptManager.GetCurrent(Page)), since the ScriptManager is defined in the master page.

Any idea on how I can solve this without having to create 2 master pages (with & without the UpdatePanel) and dynamically switching between both?

Wouter

Locate the WebpartManger in masterpage by

this.MasterPage.FindControl("yourwebpartmangerid");


Thanks for the hint. I was able to locate the scriptmanager in this way and disable the partial rendering.

However, a new problem arose after I did all this. The page showed two assert popup boxes:

"Assertion Failed: Could not resolve reference to object named "_PageRequestManager" for "dataContext" property on object of type "Sys.Binding""

"Assertion Failed: No data context available for binding with ID "" and dataPath "inPostBack" on object of type "Sys.UI.Control""

I've tracked this down to the UpdateProgress control, which still renders xml-script while EnablePartialRendering is false (see also http://forums.asp.net/thread/1250774.aspx)

I'm now trying to programmatically remove or disable the UpgradeProgress control as well, but had no luck so far :(


hello.

ah, i remember that...well, in fact, the class has 2 bugs:

1. the 1st is that it renders xml-script without checking for its visible property
2. the 2nd is that the interface is implemented explicitly without any delegation to a protected virtual method (this would let you easilly fix this).

so, your best option is to write your own updateprogress control.

Programmatically Show UpdateProgress on Content Page

Hi, this question has arisen from another thread I posted but seemed worth having its own thread. I have followed the tutorial explaining how to programmatically show an UpdateProgress control using javascript found here:

http://www.asp.net/AJAX/Documentation/Live/tutorials/ProgrammingUpdateProgress.aspx

The example works fine if I copy it on a stand alone web form, but will not work when I use it as a content page for my project's master page. My master page does not use any ajax components. What is the difference that's disabling this code?

Try replacing any instance of

$get('UpdateProgress1')

with

$get('<%= UpdateProgress1.ClientID %>')


DisturbedBuddha's post should fix your issue.

TheContentPlaceHolder control implements INamingContainer which basically appends a string to make your controls unique. By using the ClientID, you are returning the actualy ID that will be rendered.

-Damien


Thanks, I didn't realize that the control name wasn't changed otherwise. Surprisingly, it still doesn't work...until I looked at my javascript. Here's microsoft's example:

...function InitializeRequest(sender, args) { if (prm.get_isInAsyncPostBack()) { args.set_cancel(true); } postBackElement = args.get_postBackElement(); if (postBackElement.id =='Panel1Trigger') { $get('UpdateProgress1').style.display = 'block'; } }function EndRequest(sender, args) { if (postBackElement.id =='Panel1Trigger') { $get('UpdateProgress1').style.display = 'none'; } }...
As you can see 'Panel1Trigger' is also referenced by its server ID, not the ID given by the INaming container. So here is the code that works:
...function InitializeRequest(sender, args) { if (prm.get_isInAsyncPostBack()) { args.set_cancel(true); } postBackElement = args.get_postBackElement(); if (postBackElement.id =='<%= Panel1Trigger.ClientID %>') { $get('<%= UpdateProgress1.ClientID %>').style.display = 'block'; } } function EndRequest(sender, args) { if (postBackElement.id =='<%= Panel1Trigger.ClientID %>') { $get('<%= UpdateProgress1.ClientID %>').style.display = 'none'; } }...
What a pain! Thanks for your help!

Programmatically trigger modal popup

I want to write a page that checks for a cookie via Javascript and then possibly opens a modal dialog box. How do I trigger the modal popup via client side javascript?

I saw the example that comes on the modal dialog that sample page, however that works with a client side event such as a click. Can I do it without listening for an event?

Hi theregit,

In the javascript where you check the cookie, you can trigger a button.

That button's click event can then be another javascript that opens a modal window.

Trigger the button like:
var myButton = document.getElementById('myButton');
myButton.click();

Is this an answer to your question?
if you have comments/remarks/questions .. please do so!

Kind regards
Wim


Try this ,

Show and Hide ModalPopupExtender from JavaScript

Hope this helps


Phanatic,

Thank you sooo much for that post. I was having the problem with the 'null' is null or not an object error. Once I used the pageLoad() method it worked great.

Progress Bar while Page Loading In Process

Hi

i have a typical question.

I want toshow user a progress bar image and some message while page load is inprocess and once the results are rendered to the browser i want to hidethis progress bar.Can someone tell me how to approach it.I triedJavascript and Response.Flush the error i am getting is http headersalready set when ever response.redirect is came accrossed.as of othersolution I also tried showing updateprogress bar in page loading eventof pagerequestmanager its not showing update progress bar.As codingpart already,i dont want to disturb the code while inserting thistransition part of image and message,Can i know how to approach thisproblem or any other solution

Thanks

This can be done by AJAX. Hope you don't mind if I recommend you to download videos from the site.

Here's the site:http://www.asp.net/learn/ajax-videos/

Cheers,

CLIPER


What you need is a delay loading your data, try reading this posthttp://mattberseth.com/blog/2007/07/delay_load_an_updatepanel.html

Progress display priority to low

I have a page where a very large CSV response is generated on a button-click. During that action I want to show a progress which I have made an ASP.NET AJAX PageMethod for and I call it from a javascript interval. However once the processing is happening, my progress doesn't update. Either the interval is stopped by the browser or the runtime can't accept the pagemethod call because it's too busy? Is there a way around this? I tried threading, but apparently that doesn't allow returning something...

Thanks

You are missing how AJAX calls work... Once a request is made to the server it will only receive the callback when the method completes. See my previous post, here:http://forums.asp.net/p/1151473/1879009.aspx.

An approach you can use is:http://blogs.visoftinc.com/archive/2007/09/10/modalupateprogress.aspx. There isn't a real-time progress in that approach however. The process to do a "real-time" progress bar is extra overhead in the web world; animated gifs are typically used (see:http://www.ajaxload.info/ for some good graphics)

-Damien

Progressbar while the updatePanel is updating or the controls are rendering in the UpdateP

Hi Guyz,

Can anybody please tell me, how can i display a progressbar on the page with Ajax, which will stay there till the time data in the Updatepanel is loading. I have a gridview in a updatepanel which displays data from the database, it has paging enabled now what i want is when user changes the page. There should be a progressbar which says Loading ... or some message like that.

I have read some posts about UpdateProgress i think its not there in Ajax Beta 1 or 2. But there is UpdatePanelAnimationExtender.
But could not find anything useful. Is there any examples for this.

Can anybody please help.

Thanks
Amit

hi amit,

did u watched scott's video i hope it will help you. open this url in media playerhttp://download.microsoft.com/download/7/8/f/78f2d61a-74c6-47b6-835c-0d1efa5524af/ScuttGu_asp_net_atlas.wmv

or onhttp://ajax.asp.net see

Video - Developing ASP.NET 2.0 Applications using AJAX

by Scott Guthrie, General Manager, .NET Development Platform

at bottom of home page.

thanks,

satish.


Thanks satish

But its really easy with the help of updateprogress control. you can put the text you want to display while the updatepanel is updating. and that's it.

It will work for you.

Anyways thanks for your help again.

Amit


no worries amit. though lucky u working on AJAX its really wonderful but its not coming my way in my companySad.

regards,

satish.


i am just using prebuilt components, not doing my own programming with ajax.
It's really easy to use man. not a big deal.

Amit

Property Page for Controls?

Ok, I may just be a complete idiot, but are there extended property pages available for the controls in the toolkit at design time?

For instance, the PasswordStrength extender has a property calledTextStrengthDescriptions but as far as I can see, it is not on the properties page.

The documentation states it is initialized with this code:

<ajaxToolkit:PasswordStrength ID="PS" runat="server" TargetControlID="TextBox1"DisplayPosition="RightSide"StrengthIndicatorType="Text"PreferredPasswordLength="10"PrefixText="Strength:"TextCssClass="TextIndicator_TextBox1"MinimumNumericCharacters="0"MinimumSymbolCharacters="0"RequiresUpperAndLowerCaseCharacters="false"TextStrengthDescriptions="Very Poor;Weak;Average;Strong;Excellent"TextStrengthDescriptionStyles="cssClass1;cssClass2;cssClass3;cssClass4;cssClass5CalculationWeightings="50;15;15;20" />

But for the life of me, I cannot find this block of code anywhere - so I end up having to set the values in code. Can anyone tell me where the above init code is located or how to access the other non-displayed properties of a control in the designer?

Thanks!

Hi,

Please download the sample applicationhere, then open the PasswordStrength.aspx page, you will find it in the html source.

Protecting javascript based on role

To set up what i am going to ask, allow me to explain the page:

I've got a page that shows reports with a popup panel that has all sorts of options on it.... when i first load the page, i show/hide/fill these options based on Roles

The page does not do any post backs, just javascript calls to webservices and i show the report data based onthis blog post by Scott Guthrie (using a page instance, a user control and generating/grabbing the HTML)....

In the aspx markup of the page is hundreds of lines of javascript i have written over the past week, and what i am realizing is that all the script is there for the world to see regardless of role....

So where i may say: $get('drpManager') , that is a control that is only available to certain role (i set visible and enabled to false if the user isn't allowed to see it), but just seeing that in the code, a malicious user may be able to figure out how to do something that they shouldn't be allowed to...

So what I am asking/wondering is maybe some ideas to package the javascript, broken up into role specific functionality, into the page execution and spit it out (this cried out WebResource and ScriptManager.RegisterScript) based on role

Any thoughts on this or pointers?

Unfortunately ( and I hope someone with greater knowledge than I will lambast me for saying something inaccurate)... is no - there is no such thing as security when it comes to scripts. This is the only primary reason I handle everything from the server side when it comes to security specific issues...You can however authenticate using the profile feature of Ajax...but even if you use any of the number of javascript encryptors available (most will not work with Ajax anyways). You will be exposing your logic to those whom realize that you are doing something sensistive..

Naturally you could could create seperate javascripts depending on the role it would be more secure - but if you are using anything Ajax in a security related enviroment - it is my recomended best practice handle it serverside and not clientside... the less the client knows what is going on means the less a hacker knows what is going on... Ajax is afterall just a tool... and security wise - its is the the subject of numerous related security articles because there really is no framework to protect against plain text script... but I would not rely on a global and executing based upon parameters sent to the client on the client...if you must and refuse to do the stuff server side and take the perf hit while maintaining the ajax ui glitz for the customer... then send only the scripts to the client that are related for the role they have...


jodywbcb:

then send only the scripts to the client that are related for the role they have...

Apparently you missed the whole entire point of my topic and the question i asked at the very end, as the above line by you that i quoted is exactly what i was asking for ideas onhow to do...

I wasn't asking for page architecture advice... the page is big and it's fast as hell and getting/updated/refreshing sections of the report piece by piece via AJAX, which absolutely is the best way for this page to serve it's existance, now i am just asking about steps, even if it's just a little step, on keeping code out that a lesser role doesn't need

Providing Scroll Bars to update panel

Hi,
I am using ajax for loading different user controls . I have two main problems
1. I have a main page where i have 4 update panels . the structure is like the the following( i removed the atributes for each elemnet like id , runat etc
<table>
<tr>
<td><updatepanel><contenttemplate><uc1:ststicbar><ontenttemplate></updatepanel><td>
<td><updatepanel><contenttemplate><uc1:dynbar><ontenttemplate></updatepanel><td>
</tr>
<tr>
<td colspan=2><updatepanel><contenttemplate>content here<ontenttemplate></updatepanel></td>
</tr>
<tr>
<td colspan=2><updatepanel><contenttemplate><uc1:statusbar><contenttemplate></updatepanel><td>

</tr>
</table>

where i have two user controls on top
and one at the bottom representing toobars and ststus bar(bottom)
in the middle update panel i am loading different user controls.
my problems are.

1. I need the keep the top toolbars and bottom status bar always visible
ie when i load a user control in the midddle update panel if its height is more there should be a scroll bar
I tried with adiv tag for the content but not worked properly i find update panels emit div tag in the client.
is there any way to provide scrolling for the update panel.ie the div tag which is get emitted for the update panel.

Thanks and Regards
Jereesh

All the Style Tag works also with the table tr and td tag

apply ur style to the Table like

<table id=tbl1 style="OVERFLOW:auto;WIDTH:200px;HEIGHT:230px;">

<tr><td></td></tr>

</table>

It will sork fine iam using it.

any proble get back to me.


Hey,

Just put the update panel for which you wanna have the scrollbars, inside a panel saypanel1.

Set the height and width of the panel and set the scrollbar property of the panel as you like.

Saturday, March 24, 2012

Put the UpdateProgress into an AlwaysVisibleControl?

I already have an updateProgress in a master page as per below code..

Is it possible to somehow wrap this in another control and have this control referenced by an AlwaysVisibleControl. Therefore when a user needs to scroll down a page the update progress will always be visible.

Thanks

N

<

atlas:UpdateProgressid="loadingProgress"runat="server"><ProgressTemplate><divstyle="text-align: right;"id="loadingAnimation"><imgid="img9"src="images/indicator3.gif"title="Loading"alt=" Loading"border="0"><asp:LabelID="Label1"runat="server"Font-Names="verdana"Font-Size=8ForeColor=silverText="Working..."></asp:Label></div></ProgressTemplate></atlas:UpdateProgress>Hi niallhannon,

There shouldn't be any reason you can't do this to my knowledge... are you having a problem trying to?

Thanks,
Ted

You are right, it does work, I must have been doing something wrong.

Thanks for the reply.

N


Please share what you did. I'm trying to do the same!

Never mind. I figured it out myself. The AlwaysVisibleControlExtender needs to be inside the <ProgressTemplate> tags. For example:

<%@.RegisterAssembly="AtlasControlToolkit"Namespace="AtlasControlToolkit"TagPrefix="cc2" %>

<atlas:UpdateProgressID="ProgressIndicator"runat="server">
<ProgressTemplate>
<asp:Panelid="progressArea"runat="server">
<br/>Loading, please wait...
<asp:ImageID="LoadingImage"runat="server"ImageUrl="~/Images/spinner.gif"/>
</asp:Panel>
<cc2:AlwaysVisibleControlExtenderID="AlwaysVisible1"runat="server">
<cc2:AlwaysVisibleControlPropertiesTargetControlID="progressArea"/>
</cc2:AlwaysVisibleControlExtender>
</ProgressTemplate>
</atlas:UpdateProgress>

That works great then.


Hi Jason,

I hadto the same problem as you when I tried this last week, and ended up putting the AlwaysVisibleExtender in the ProgressTemplate.

However I found that every few updates on the same page (4 or 5?) would pop a javascript message box saying "Unspecified Error". Everything else seems to work ok.

I was wondering if you have the same problem?

~Brett


No, I've not seen any issues like that. I'm using the June CTP if that helps. I'll keep an eye on it though as its an app I'm actively developing at the moment.

Are you sure the javascript error is related to the location of the AlwaysVisibleControlExtender?


I'm Using April, perhaps it was fixed. The Javascript error was definately related to AlwaysVisibleControlExtender - once I removed that from my form the error message stops. Add it back = message returns

~Brett


Try using the June CTP. I believe there are no breaking changes (at least there wasn't for me!).

Also, could you post your AlwaysVisibleControlExtender markup? Unless its simple, maybe there's an issue within it. Just a thought.


I tried this with the June CTP and it seems it works fine.

~Brett

Query string is diappearing, when using MaskedEditExtender

I had a page, where parameters were passed through query string.

I decided to include MaskedEditExtender in this page.

<cc1:MaskedEditExtender ID="meeIP" runat="server"
TargetControlID="txbIP"
Mask="999.999.999.NNN"
MessageValidatorTip="true"

MaskType="None"
InputDirection="RightToLeft"

</cc1:MaskedEditExtender>

After this my query string disappeared.

I cannt get the value from query string.( Request["siteID"];)

But when I comment out the ajax control everething gets fine and my query string is visible again.

What should I do?

Its my first time, when I'm trying to use ajax.asp.net.

Help...

Help.

Help!

Does anybody has an answere?

Question About AutoComplete

Hello,

I have setup a page containing two text box which utilize the AutoComplete Extension and work perfectly (thanks to the video helps), but I would like to extend this a bit. I would like to use the variable that had been put into the first text box, to restrict what is displayed in the second auto complete. Basically, once I am within my autocomplete.asmx file, how to I get the variable of what was in the first text box to pass into my stored procedure?

Thanks,

Chris

What you want to do is use the contextKey parameter. It's described in thedocumentation for the extender.


Hrm, this is very close, but I still do not see how to assign the text, or a variable, to the ContextKey? I can see how to pass a static piece of text in, which I have had success with, but have not had to much luck with the variable.

Thanks,

Chris


You can use $find('AutocompleteExtenderClientID').set_contextKey() to set that on the client side. So, you'd want to use $addHandler to handle the context textbox's onchange event and update the autocomplete extender's contextKey with the textbox's new value.

Is this what you were talking about? I get some errors when I try to compile it. Also, is there a way to Prepend the text it is going to set?

Thanks so much,

Chris

1<asp:TextBox ID="PortName" runat="server" OnTextChanged=$find('AutoCompletePortName').set_contextKey()></asp:TextBox>23<cc1:AutoCompleteExtender ID="AutoCompletePortName" runat="server" TargetControlID="PortName" ServicePath="AutoComplete.asmx" ServiceMethod="GetCompletionList" MinimumPrefixLength="3" CompletionSetCount="5" ContextKey=$addHandler UseContextKey=True>4 </cc1:AutoCompleteExtender>5


You might be able to do this, but I haven't tested it:

<cc1:AutoCompleteExtender ID="AutoCompletePortName" runat="server" TargetControlID="PortName" ServicePath="AutoComplete.asmx" ServiceMethod="GetCompletionList" MinimumPrefixLength="3" CompletionSetCount="5" ContextKey="$get('<%= PortName.ClientID%>').value" />

If it works, that's going to be the easiest way to do it. Also, you don't have to explicitly set UseContextKey. If a ContextKey is specified, it will automatically use it.

$addHandler is a little bit more complicated than that. You can see a few examples of using it here:http://encosia.com/2007/11/15/exploring-one-of-ms-ajaxs-often-overlooked-features/

Question about DropDownList behavior inside an UpdatePanel

Hi,

I have an application that has two DropDownLists on a page. The first is just a plain ASP DropDownList; the second is an ASP DropDownList inside an UpdatePanel. The page also contains a label inside a second UpdatePanel.

When the item in the first DropDownList is changed, the second DropDownList is populated. When the item in the second DropDownList is changed, the Label's text is changed.

I have noticed that when the first DropDownList changes, the second DropDownList "flickers" as it populates. When I select a value in the second list, the label updates as it should, but the second DropDownList again flickers, as if it is also being refreshed. Both UpdatePanels have UpdateMode="conditional" set.

My question is whether this is normal behavior on the second DropDownList, since it is inside an UpdatePanel, or do I have something set wrong? It's a minor issue, but kind of annoying since I would not expect to see any kind of refresh when changing a value in the second DropDownList.

I have included a simple example which shows what I'm talking about. Thanks as always for your help!

<%@dotnet.itags.org.PageLanguage="vb"AutoEventWireup="false"CodeBehind="Default.aspx.vb"Inherits="DropDownTest._Default" %>

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

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

<headrunat="server">

<title>Untitled Page</title>

</head>

<body>

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

<asp:ScriptManagerID="ScriptManager1"runat="server"/>

<div>

<ASP:DROPDOWNLISTid="DropDownList1"autopostback="true"runat="server"width="110px"></ASP:DROPDOWNLIST>

<br/><br/><br/><br/><br/><br/>

<ASP:UPDATEPANELid="UpdatePanel1"runat="server"updatemode="conditional">

<CONTENTTEMPLATE>

<ASP:DROPDOWNLISTid="DropDownList2"autopostback="true"runat="server"width="110px"></ASP:DROPDOWNLIST>

</CONTENTTEMPLATE>

<TRIGGERS>

<ASP:ASYNCPOSTBACKTRIGGERcontrolid="DropDownList1"eventname="SelectedIndexChanged"/>

</TRIGGERS>

</ASP:UPDATEPANEL>

<br/><br/><br/><br/><br/><br/>

<ASP:UPDATEPANELid="UpdatePanel2"runat="server"updatemode="conditional">

<CONTENTTEMPLATE>

<ASP:LABELid="Label1"runat="server"text="Label"></ASP:LABEL>

</CONTENTTEMPLATE>

<TRIGGERS>

<ASP:ASYNCPOSTBACKTRIGGERcontrolid="DropDownList2"eventname="SelectedIndexChanged"/>

</TRIGGERS>

</ASP:UPDATEPANEL>

</div>

</form>

</body>

</html>

PartialPublicClass _Default

Inherits System.Web.UI.Page

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

IfNot IsPostBackThen

Me.DropDownList1.Items.Clear()

Dim objListItemAs ListItem

objListItem =New ListItem

objListItem.Text = 1

Me.DropDownList1.Items.Add(objListItem)objListItem =New ListItem

objListItem.Text = 2

Me.DropDownList1.Items.Add(objListItem)

objListItem =New ListItem

objListItem.Text = 3

Me.DropDownList1.Items.Add(objListItem)

EndIf

EndSub

PrivateSub DropDownList1_SelectedIndexChanged(ByVal senderAsObject,ByVal eAs System.EventArgs)Handles DropDownList1.SelectedIndexChanged

Me.DropDownList2.Items.Clear()

Dim objListItemAs ListItemobjListItem =New ListItem

objListItem.Text = 9

Me.DropDownList2.Items.Add(objListItem)

objListItem =New ListItem

objListItem.Text = 8

Me.DropDownList2.Items.Add(objListItem)objListItem =New ListItem

objListItem.Text = 7

Me.DropDownList2.Items.Add(objListItem)

EndSub

PrivateSub DropDownList2_SelectedIndexChanged(ByVal senderAsObject,ByVal eAs System.EventArgs)Handles DropDownList2.SelectedIndexChanged

Me.Label1.Text =Me.DropDownList1.SelectedValue +Me.DropDownList2.SelectedValue

EndSub

EndClass

Does this happen in both FF and IE6/7?


Definitely in IE6, as that's my default right now. I tried Firefox, and it does not seem to have this issue.

I also noticed that in IE6, when I select the item in the first list, the item is highlighted (dark blue background) until I move focus. When I select an item in the second list, the highlighting is removed. This could simply be because the focus shifted to the label. Neither list stays highlighted in Firefox.

So, it appears that it may be an IE quirk. Has anyone else seen this issue or found a work around? I should be getting IE7 on my PC in the next week or two, so maybe that will solve it!


IE6 blows. I know - Shocking news!

Try it out on IE7 and see if that fixes your problem.

I realize that some of the world is still using IE6, some can't even upgrade to 7 (ie. Win2K users) but I hate coding for that browser.


You should set the property of the UpdatePanel named "UpdatePanel2":updatemode="all"