Showing posts with label asp. Show all posts
Showing posts with label asp. Show all posts

Wednesday, March 28, 2012

Extenders NOT Doing Anything?

I've just reviewed "#36 – How Do I: Use the ASP.NET AJAX MaskEdit Controls?". I ran the finished sample code (as downloaded) on VWD 2005 EE and it all works "as advertised" – all of the functionality is definitely there.

HOWEVER, when I copied the project file up to TWO different hosting services (both equipped with the current "AjaxControlTookit.dll" [and dll.refresh] and ".pdb" files in a "/Bin" directory at the root level of the logical "wwwroot" the application starts without error but then nothing really IS "extended" in the three sample Textbox controls. HUH? I emphasize that this happens on TWO separate hosting services (one if GoDaddy which has been shown to work with ASP.NET 2 and the other is on UltimaHosts.net which has also run 'normal' ASP.NET 2 applications).

I fear I'm missing something fundamental here. Any ideas?

Mahalos in advance …J KevInKauai

Does the bin folder also contain the 2 dll's for the ajax core?

System.Web.Extensions.dll

System.Web.Extensions.Design.dll


Hi, Wim, and thanks for the attempt at guidance.

I'm unclear about whether you mean a "/Bin" directory beneath each Application/Project or at the root of the web site (which is what I have). (It would seem awfully space-consuming to have to have it in EACH Application/Project, right?)

Here's what I've got:

problem summation

SO WHERE'S the handy-dandy goof-proof "guide to deploying ASP.NET/AJAX-ified applications on your Server" ?

The devil seems to be in the details, as usual!

mahalo for any guidance ... :) KevInKauai

P.S. The results are identical in the following browsers: FireFox 2.0, IE 70.5730.11 and Safari PC 3.0 (522.11.3).


Hi,

You'd better install the Ajax extension on the server first. It can be downloaded here: http://ajax.asp.net/downloads/default.aspx?tabid=47


Hi, Raymond - -

Do the screen captures above not show that the "required" libraries are there? According to my download directory, I downloaded "ASPAJAXExtSetup.msi" (around May 15) and ran into, then used what I assumed are the required items (as indicated in the screen shots).

I don't think you're telling me to download this again "just for fun", are you?

Mahalo ... :) KevInKauai


Hey,

Ok, A website has a bin directory: For example: c:\Inetpub\wwwroot\MyWebSite\bin
The above tells me I have a website called MyWebSite and it has a bin-folder.

I don't think that MyWebSite can use a bin folder located here: c:\Inetpub\wwwroot\bin
AND that is just what your pictures tell me. So the bin folder should be inside the WebSite directory.

If you want to use dll's for more applications and you don't want to copy the dll's to every bin of every website that uses them, you should install those dlls in the GAC (Global Assembly Cache).

Note that the dll's you want to use in serveral applications should be installed in the GAC of the WebServer.

Also note that the installation of dll's in the GAC is best done by using the GACUTIL.EXE utility which can be started from command line.

Hope this helps!
Wim


KevInKauai:

Hi, Raymond - -

Do the screen captures above not show that the "required" libraries are there? According to my download directory, I downloaded "ASPAJAXExtSetup.msi" (around May 15) and ran into, then used what I assumed are the required items (as indicated in the screen shots).

I don't think you're telling me to download this again "just for fun", are you?

Mahalo ... :) KevInKauai

The point of my suggestion is that it's not sufficient to deploy it by simply putting it in the bin folder. Because some of the operations performed by the AJAX extension require full trust permission. To install it will installer will add it into GAC automatically and run with full trust permission.

You can try Wim's suggestion to install it into GAC manually.

You may also tryconfiguringyou web application to run in full trust mode in web.config.


Raymond Wen - MSFT:

The point of my suggestion is that it's not sufficient to deploy it by simply putting it in the bin folder.

Hey Raymond,

Ok, this is a bit off topic, but on my webserver, their is NO Ajax, nor the toolkit installed, and just by putting the 2 ajax dll's and the toolkit dll in the binfolder of my website on the webserver, all the ajax and toolkit functionallity works!

Greetz,
Wim


Hi, Wim - -

Thanks for your pointers and perhaps I should have made it clearer that I'm in a "shared hosting" situation -- where I do not control things like whatever the "GAC" is. According to their notes on AJAX, they have installed "what you need" there. It's the add-on stuff that wants a proper home. I had assumed that ONE /Bin directory at the root of my website (which has old-time FrontPage things which want to be calling out to new-style ASP/AJAX application pages) would suffice.

Are you saying that each application sub-directory is going to need a /Bin with extra copies of these various AJAX components?

If anyone knows where the CLEAR and SIMPLE "How to use AJAX in a Shared Hosting Environment" installation guide is, I'd sure appreciate a push in that direction!

Mahalo ... :) KevInKauai


KevInKauai:

Are you saying that each application sub-directory is going to need a /Bin with extra copies of these various AJAX components?

Hi,

For as far as I know this is going to be the procedure. If someone else knows a way to create a central storage for application-wide-dll's, please let us knowWink (it has to be possible :) )

Normally the GAC offers a solution to store application wide dll's in one place. But for shared hosting where you don't have full control over the webserver that isn't so easy.

Extenders inside template column of a gridview

[THIS IS FOLLOWED FROM POSThttp://forums.asp.net/thread/1498604.aspx in ControlToolKit forum, where I have been suggested to post in this forum]

I have a gridview that contains a template column, with 2imageButtons inside it (Basically Edit Item and Delete Item) and aconfirmButtonExtender linked on the delete image button. Everything wasworking well in Beta 2, but in RC1, in design time, it does not renderthe gridview, saying that a scriptmanger is required and must existbefore any control on the page... It works great at runtime, but it isquite annoying at design time...

Will this be fixed in a future release?

I have posted an example of page that reproduce the issue in the other post (see link at top of message)

Thanks!This is a known issue with Ajax RC 1.0. Wish this issue will be resolved in ASP.NET AJAX RTM.

Extenders briefly appearing on a page load

Hi there

I am using the modalpopup and calender extenders from the toolkit in my ASP.NET code.

The page they are on is a content page (I am using master pages).

They both work. However, when the page initially loads the extender(happens on both) flickers on the screen and then hides itself!?!?!

Does anyone have any ideas?

Many thanks

Mike

Hi Mike,

It seems a full postback is occurring according to your description. Please make sure the targetControlid is properly set the button that triggers a full postback.


Hi there

Thanks for the help. I have set the control IDs correctly.

The calender popup I have working, I had to set the visibility to false in the style.

However, for the modal popup I tried this and it doesn't show up at all.

Any more ideas I can try to stop the modal popup from flickering initially??

Cheers

Mike


Try setting the style as... style="display: none;"


Can you post a stripped sample?


Hi

I tried that also and it stops my popup from being displayed at all. (However, on a side note, when I do do this, as well as not showing my poopup it seems to keep adding "invisible" stuff to the side of my page, makes my scroll bars appear and the page keeps getting wider and wider!!! Very very strange and freaky!!!)

The code for my modalpopup is:


 <asp:Button runat="server" ID="testbut" text="popup test" OnClick="testbut_Click" CssClass="hiddenbutton"/> <asp:Panel ID="Panel1" runat="server"> <asp:Panel ID="Panel3" runat="server" CssClass="modalPopup"> <div> <p class="title">AudioPC Navigator</p> <br /> <p> AudioPC Navigator will launch each Audiosoft component into a new window, but supports tabbed browsing if your browser is configured to do so. </p> <br /> <p> For details on how to set your system to tabbed browsing <a onclick="help('TabbedBrowsing');return false;">click here</a> </p> <br /> <p> <input type="checkbox" name="check" id="InitialHelpCheckbox" /> <label for="InitialHelpCheckbox" class="sampleStyleC" style="padding: 3px;">Do not show this message again</label> </p> <br /> <p style="text-align: center;"> <asp:Button ID="OkButton" runat="server" Text="OK" /> </p> </div> </asp:Panel> </asp:Panel> <ajaxToolkit:ModalPopupExtender ID="InitialHelpModalPopup" runat="server" PopupControlID="Panel1" BackgroundCssClass="modalBackground" OkControlID="OkButton" OnOkScript="onOk()" DropShadow="true" Drag="true" PopupDragHandleControlID="Panel3" TargetControlID="testbut"/>

<asp:Button runat="server" ID="testbut" text="popup test" OnClick="testbut_Click" CssClass="hiddenbutton"/>

<asp:Panel ID="Panel1" runat="server">
<asp:Panel ID="Panel3" runat="server" CssClass="modalPopup">
<div>
<p class="title">AudioPC Navigator</p>
<br />
<p>
AudioPC Navigator will launch each Audiosoft component into a new window, but supports tabbed browsing if your browser is configured to do so.
</p>
<br />
<p>
For details on how to set your system to tabbed browsing <a onclick="help('TabbedBrowsing');return false;">click here</a>
</p>
<br />

<p>
<input type="checkbox" name="check" id="InitialHelpCheckbox" />
<label for="InitialHelpCheckbox" class="sampleStyleC"
style="padding: 3px;">Do not show this message again</label>
</p>
<br />
<p style="text-align: center;">
<asp:Button ID="OkButton" runat="server" Text="OK" />
</p>
</div>
</asp:Panel>
</asp:Panel>


<ajaxToolkit:ModalPopupExtender ID="InitialHelpModalPopup" runat="server"
PopupControlID="Panel1"
BackgroundCssClass="modalBackground"
OkControlID="OkButton"
OnOkScript="onOk()"
DropShadow="true"
Drag="true"
PopupDragHandleControlID="Panel3"
TargetControlID="testbut"/>

And the style for the popup is:

.modalPopup {
background-color:#e4e4e4;
border-width:1px;
border-style:solid;
border-color:Black;
padding:1px;
width:350px;
}

Any more ideas?

Thanks in advance

Mike


Why I can't see the flicker thing ? My code:

<%@. 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 testbut_Click(object sender, EventArgs e) { }</script><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server"> <title>Untitled Page</title> <style type="text/css"> .modalPopup { background-color:#e4e4e4; border-width:1px; border-style:solid; border-color:Black; padding:1px; width:350px;} </style></head><body> <form id="form1" runat="server"> <div> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <asp:Button runat="server" ID="testbut" text="popup test" OnClick="testbut_Click" CssClass="hiddenbutton"/> <asp:Panel ID="Panel1" runat="server"> <asp:Panel ID="Panel3" runat="server" CssClass="modalPopup"> <div> <p class="title">AudioPC Navigator</p> <br /> <p> AudioPC Navigator will launch each Audiosoft component into a new window, but supports tabbed browsing if your browser is configured to do so. </p> <br /> <p> For details on how to set your system to tabbed browsing <a onclick="help('TabbedBrowsing');return false;">click here</a> </p> <br /> <p> <input type="checkbox" name="check" id="InitialHelpCheckbox" /> <label for="InitialHelpCheckbox" class="sampleStyleC" style="padding: 3px;">Do not show this message again</label> </p> <br /> <p style="text-align: center;"> <asp:Button ID="OkButton" runat="server" Text="OK" /> </p> </div> </asp:Panel> </asp:Panel> <ajaxToolkit:ModalPopupExtender ID="InitialHelpModalPopup" runat="server" PopupControlID="Panel1" BackgroundCssClass="modalBackground" OkControlID="OkButton" OnOkScript="onOk()" DropShadow="true" Drag="true" PopupDragHandleControlID="Panel3" TargetControlID="testbut"/> </div> </form> </body></html>

Extender Control properties in a switch/case

Hello,

I have problems using properties of an Extender Control in a switch/case selection.

I wrote an ASP.NET AJAX Extender Control to control a GridView with keyboard shortcuts. For that, the user can configure declaretively what keys to use for e.g. paging in the GridView. The key values are mapped to properties in the JavaScript part of the Extender Control (Sys.UI.Behavior class).

In a handler function I determine which key the user has pressed and call the porper _postBack. This works fine with if/else, e.g. if (KeyEvent.keyCode == this._delKeyCode). But with switch/case, e.g. switch (KeyEvent) { case this._delKeyCode: ... break; .. the pressed key is not determined and nothing happens with the GridView. There are also no JavaScript errors. It seems, that with switch/case a control property can't be determined as with if/else.

Thank You

Regards

Rolf

The switch should be:

switch (KeyEvent.keyCode) {
case this._delKeyCode:
// Something
break;
}

-Damien


Thanks Damien,

but sorry it is a typo in my post. I'am actually using

switch (KeyEvent.keyCode) instead ofswitch (KeyEvent) as I wrote. So I'am actually using the switch statement you suggest.

Regards

Rolf


My only guess why it isn't working is because you are comparing against a variable (e.g. this._delKeyCode), try using the actual numeric key code...

-Damien

Monday, March 26, 2012

Exposing Web Services from an ASPX page does not work

Hi All,

I am working with ATLAS technology. i am trying to imitatehttp://atlas.asp.net/quickstart/atlas/doc/services/default.aspx#webpage
"Exposing Web Services from an ASPX page"

i am having an aspx page which is inherited from our own Page class not from System.Web.UI.Page.

public partial class MainSearchPage : some namespace.MyPage

but this example does not work in this context.because in javascript, function OnWebRequestComplete1(result) returns null as result.

please help me in this issue.

thanks
Jaideep

hello.

well, i think that it should work. here's an example:

pypage.cs
namespace Test
{
public class MyPage:Page
{
[WebMethod]
public string HelloWorld(string s)
{
return "Hello '" + s + "'";
}
}
}

now, the aspx page:


Untitled Page

function handle()
{
PageMethods.HelloWorld( "Luis", handleComplete );
}

function handleComplete( res )
{
alert( res );
}

here everything is working properly...

Yes, this should work. To debug your issue, I would try:

Check on the server whether your method gets called at all.

yes, my server side code in code behind of aspx is not getting called.
in javascript side:

function handle()

{

PageMethods.HelloWorld("jaideep", handleComplete );

}

function handleComplete( res )

{

debug.dump(res,"Result",true);

alert( res );

}

in debugger, result is null.also my aspx is having one user control also.i tried to put debug in my code behind.but function HelloWorld is not getting called.

any clue as to what is happening.
thanks

jaideep


after viewing request/response in Fiddler ,i got a message indicating a corrupted viewstate.
same is the problem in following post:
http://forums.asp.net/1205269/ShowPost.aspx "ViewState and Atlas ".
and as per the instruction given , i removed "type =="hidden" condition from file
Atlas.js on line 3495.and now it is working!! but this approach is correct or not?
please let me know about this.
Thanks

JAideep


Copying my reply from the other thread:

I tried a few things, but was not able to repro. Could you give this a try with the March CTP to see if it still happens?

thanks,
David

Exposing methods in ASP.NET AJAX Control Project

I've read every bit of documentation that I could find online (which isn't a lot) about creating your own extender with the ASP.NET AJAX Control Project. There are lots of examples about how you expose the properties in the Extender.vb or Extender.cs file, which passes the values down to the .js file. But is it possible to expose callable methods? I can add handlers forevents, but what about methods you can call at any time?

If anyone can give me an example of the proper syntax to do this, it would be greatly appreciated. Thanks.

You can't expose methods from the .cs or .vb file of your control; you'll need to use webservices or pagemethods to call a server method.

I don't want to call a server method, I want to expose a function in the Behavior.js.


Do you mean callable by JavaScript or Server-Side Code ?

all methods in your behavior.js in the Prototype section are callable methods.

You can call methods using the

$find(BehaviorID).Method() notation


Thank you for the response. That's what I needed, but just out of curiosity, is it possible to "expose" those methods to the servers side... much in the same way that the properties in the extender.cs file exposes the properties in the behavior.js file?


No.

The properties in the .cs file will be injected into the output html, and some initialization logic implemented in javascript is responsible for initializing the component with those properties.

Basically, server side object and client side object can't access each other directly.

Export to Microsoft Excel

Hello,
IE Functionality of Exporting tables to Microsoft Excel doesn't work properly when used with Asp.NET AJAX,

it always exports the first loaded data ignoring any updates done through AJAX Asynchronous post back

i.e. if a page is loaded with data X and then updated using AJAX update panel and
returned data Y then using Export to Microsoft Excel on this page will export
the first data X and not data Y


how can this be fixed?

Appreciate your help in advance.

maybe you can put some code here so that we can know what actually happen.

currently it work fine to me


Hello,

This is a sample of the code unfortunately i wanted to upload the solution but was not able to add files.

I have a master page, default.aspx and dataclass.cs

Appreciate your help in advance.

"C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
 
"Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> "ScriptManager1" runat="server">
"DropDownList1" runat="server" AutoPostBack="True"> A B

"UpdatePanel1" runat="server"> "GridView1" runat="server" DataSourceID="ObjectDataSource1"> "ObjectDataSource1" runat="server" TypeName="DataClass" SelectMethod="FillData"> "DropDownList1" Name="text" PropertyName="SelectedValue" Type="String">

using System;using System.Data;using System.Configuration;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;public partialclass _Default : System.Web.UI.Page {protected void Page_Load(object sender, EventArgs e){if(!IsPostBack)DropDownList1.SelectedIndex = 1;}}public class DataClass{public DataClass(){//// TODO: Add constructor logic here//}public static DataTable FillData(string text){DataTable dt =new DataTable();dt.Columns.Add("Column");for (int i = 0; i < 100; i++){dt.Rows.Add(new object[] { text });}return dt;}}

Export to excel and UpdatePanel problems

As I have noticed myself and while looking around for a good answer, a normal asp button to export to excel does not work inside UpdatePanels since Response lines are not viable inside UpdatePanels. It throws an exception that states something to same affect, "common causes for this error are when the response is modified", etc.

I have looked around and was not able to find a complete answer to work around this problem. The shortened code that I am using is below:

Response.ContentType = "application/vnd.ms-excel"
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls")
Response.Charset = ""
EnableViewState = False
Controls.Add(frm)
frm.Controls.Add(gv)
frm.RenderControl(hw)
Response.Write(tw.ToString())
Response.Flush():Response.Close():Response.End()

I guess the question is obvious... Is there a clean way around this besides taking the button out of the UpdatePanel? I say this since it does look silly to have one button hanging out by itself in the corner of the page somewhere... I am still new to this so I would much appreciate it if you could "dumb" down the answers a bit.

A bit off topic but would there be a way to handle this on the master page? I believe I just asked two questions ( 1. Update Panel and export to Excel issues, and 2. How to handle this in a master page) but I am mainly focused on the Export issue.

I am able to provide further information as needed. Thanks in advance to all.

First I believe you don't want to add an UpdatePanel around the response.

However why are you doing this? Response.Flush():Response.Close():Response.End()?

Just use Flush but do not close the Response


I saw both ways on the web in different threads that use both ways, without the close and end and with the close and end. However, having the habit of closing what I open, I naturally went with closing it.

BTW, the close and end did not seem to be the cause of the problem as the export as the same problem persists.


I met this problem too. when I put the export buttom into a updatepannel, it will display some javascript error. I think the most possibility of this problem that is you put the Response.contentType in the code as updatePannel use the XMLHTTP to aysn communicate with the server.

Response.ContentType = "application/vnd.ms-excel"

Response.AddHeader("content-disposition", "attachment;filename=FileName.xls")

Big Smile

Executing inline JavaScript on load

I have a rather complex ASP.NET control -WebDialog - that I'm trying to get working within Atlas' UpdatePanel.

The way the control currently works is by outputting JavaScript in its render method which is executed by the browser on load. The problem is that when an UpdatePanel is refreshed Atlas doesn't seem to execute inline scripts and so nothing happens.

I have tried moving outputting the JavaScript from the control's render method to its PreRender and then passing the script to RegisterClientScriptBlock, which Atlas does execute. While this method works great in simple scenarios, when the dialog has form controls like TextBox and Button it errors. Since I'm manually calling RenderControl on the nested content, and outside of the form's render, VerifyRenderingInServerForm throws an exception.

I don't want everyone who uses the control to have to use a custom page with VerifyRenderingInServerForm overridden.

Is there a solution that will update when an UpdatePanel refreshes yet works with forms controls and isn't obtrusive to the user developer?

hello.

i doubt it...i think that the only option is sending the javascript to the client though the clientscriptmanager class...


If I did that then I'd be dependant upon Atlas and have to include it's dll with my installer and output all it's JavaScript to the page which I don't want to do.
From what I'm reading, I believe that your JS code is registering with the window's onload event. The first time your page loads the window.onload event occurs, but subsequent partial postbacks don't cause the window.onload event to occur again.

Your thoughts of registering the script with RegisterClientScriptBlock (or RegisterClientStartupScript) seem to be on the right path. I'm not real sure from your posts why your having to manually call RenderControl (shouldn't the controls be added to the parent control's control collection?), but executing inline JS code on load is possible on an UpdatePanel refresh by registering with the ClientScriptManager.

- Joel

hello.

James Newton-King:

If I did that then I'd be dependant upon Atlas and have to include it's dll with my installer and output all it's JavaScript to the page which I don't want to do.

hum...i'm following you...you say that you don't want to be dependant upon atlas ( i think you're talking about the server side dll?)...but you also say that you have the control placed inside an updatepanel. the only way you'll use a panel is if you add the atlas dll to your app!

one more thing: if you're using asp.net (i assume you are) then you can use the clientscriptmanager without any problems since it was introduced in asp.net 2.0 to handle client script registration.


Luis Abreu:

hello.

James Newton-King:

If I did that then I'd be dependant upon Atlas and have to include it's dll with my installer and output all it's JavaScript to the page which I don't want to do.

hum...i'm following you...you say that you don't want to be dependant upon atlas ( i think you're talking about the server side dll?)...but you also say that you have the control placed inside an updatepanel. the only way you'll use a panel is if you add the atlas dll to your app!

one more thing: if you're using asp.net (i assume you are) then you can use the clientscriptmanager without any problems since it was introduced in asp.net 2.0 to handle client script registration.


Obviously if the dialog was inside an UpdatePanel then the app would be using Atlas but this control is also for regular ASP.NET 2.0 users. They're the reason I don't want to become dependant upon Atlas.

Sorry, I confused the ScriptManager in Atlas with the ClientScriptManager in ASP.NET 2.0. I am already using the ClientScriptManager (RegisterClientScriptBlock is a method on it) to register the script so I thought you must have meant the Atlas one. The problem I'm having using RegisterClientScriptBlock is that when I register the JavaScript and render the html in PreRender, ASP.NET throws an exception. It doesn't allow form form controls to be rendered outside of the form.

Anyway, I've come up with a solution that appears to work:
I'm rendering the HTML like you usually would on a page but inside a hidden div and outputting the other JavaScript using RegisterStartUpScript so that it works with Atlas's UpdatePanel. When the dialog is displayed I copy the HTML out from the hidden div into the dialog.

Saturday, March 24, 2012

Exception with Asp.net Ajax 1.0 beta 2 + VS.net

Hi,

I have installed Asp.net Ajax 1.0 beta 2.0 on VS 2005. but whenever I create any new website using asp.net template, VS2005 is throwing following exception. I tried to installed couple of times but everytime VS.net is throwing same exception

"Package Microsoft.Web.AJAXExtension.Designer.VisualStudioToolbox.AJAXExtension,Version=1.0.61025.0,Culture=neutral, PublicKeyToken=null' has failed to load properly (GUID = {CF28F3C7-5DEE-44D1-9B49-E6EB5FD0E186})"

Thanks

The problem is in the?"PublicKeyToken=null".Try?to uninstall?Ajax?Beta?2?and?create?a?new?asp.net?website?to?
check?if?it?works. If?not, maybe?the?problem?is?in?Visual?Studio?.Net?2005. Otherwise?try?to?reboot?your?PC?and?re-install?Ajax?Beta?2?to?your?PC.?Please?give?us?a?reply?after?you?try?it.

Hi ,

Thanks for information. I found some problem in machine.config. after re-installed vs.net 2005, it is workign fine.

Thanks.

Exception while adding ToolkitScriptManager dynamically in OnPreInit event

Hi,

I am trying to add ToolkitScriptManager dynamically as suggested in threadhttp://forums.asp.net/p/1039254/1777798.aspx in OnPreInit event. But I am getting exception "The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)." What could be reason?

Here is code...protectedoverridevoid OnPreInit(EventArgs e)

{

if (ToolkitScriptManager.GetCurrent(this.Page) ==null)

{

ToolkitScriptManager Manager =newToolkitScriptManager();

Manager.EnablePartialRendering =true;foreach (Control cinthis.Controls)

{

if (cis System.Web.UI.HtmlControls.HtmlForm)

c.Controls.AddAt(0, Manager);

}

}

}

Here is exception

The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).

Description:An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details:System.Web.HttpException: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).

Source Error:

Line 519: if (c is System.Web.UI.HtmlControls.HtmlForm)Line 520:Line 521: c.Controls.AddAt(0, Manager);Line 522: }Line 523: }

Any idea what could resolve this issue?

Thanks, V

Hivishant.patel,

Thanks for your post!

As far as I know, This error happens when asp.net encounterscodeblocks like <%= %>,in a UserControl andthecode-behindthe UserControl is trying to modifythecontrolscollection ofthe page (usually a LoadControl statement).

Nice solutions:

The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).

TheControlscollectioncannotbemodifiedbecausethecontrolcontainscodeblocks

Solution detail snippet:

The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).

Now I feel like a complete *** to never have run into this before. That's one hell of an assumption to miss about ASP.NET it seems. I have tons of pages where there's <%= %> markup on it. Especially in script code to get the appropariate ClientID:

<%= this.txtCompany.ClientID %>

Luckily there's a workaround for code like this by using DataBinding expressions instead:

<%# this.txtCompany.ClientID %>

This works fine for simple expressions. The difference here is that <%= %> expressions are embedded into the ASP.NET output as part of the generated Parse Tree class, whereas the <%# %> expressions are embedded at runtime.

Another workaround is to force any script code into the content of a server control and remove it from the Page class or the Content container that you're adding controls to.

<div runat="server">

<script type="text/javascript">

function ShowCreditCard()

{

var IsPayPal = false;

for(x=0; x<4; x++ )

{

var ctl = $("<%= this.txtCCType.ClientID %>_" + x.toString());

if (ctl == null)

break;

if (ctl.value == "PP" && ctl.checked)

{

IsPayPal = true;

break;

}

}

var loCC = $("<%= this.trCreditCard.ClientID %>");

if (loCC == null)

return;

var loCC2 = $("<%= this.trCreditCardExpiration.ClientID %>");

if (IsPayPal)

{

loCC.style.display = "none";

loCC2.style.display = "none";

}

else

{

loCC.style.display = "";

loCC2.style.display = "";

}

}

</script>

</div>

This works as well, although this is also pretty ugly. In my case this is probably the easier solution though, because most of my markup expressions are doing exactly what's happening above: Embedding ClientScript Ids into JavaScript.

I still don't see why the control collection can't be modified if there are <% %> blocks on the page. Those blocks are just turned into Response.Write() commands, or raw code blocks. I don't see how this affects the Controls collection that would require this sort of error.

In my situation here I was able to get by just switching to <%# %> or wrapping sections with a server tag. Even if that's not an option the above code captures the error and goes on. This means the warning icons don't show up, but the rest of the error handling showing the summary and error control linking etc. all still works.

Can anybody think of another more reliable way to inject markup into the page dynamically from outside of the control rendering? In a previous rev of my databinding tools I had custom controls and I simply took over post rendering which was reliable. But this is not so easily done externally… I can think of possibly hooking up the Render method and calling back into my custom control, but man does that seem ugly.

Related Posts:

The Controls collection cannot be modified because the control...

Error:The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)

The Controls collection cannot be modified because the control contains code blocks ...


Jin-Yu Yin - MSFT:

This error happens when asp.net encounterscodeblocks like <%= %>, or <%# %>

Hi Jin-Yu Jin,

This is not correct, but your "Solution detail snippet" also clear about this.

So

The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)

only shown when you try to modify acontrol's control collection, when there is <%= %> in thecontrol's root childs . <%# %> not problem at all.

Example:

<asp:PlaceHolder runat="server" id="WeDynamicallyAddControlForThisInCodeBehind">

<%= DateTime.Now.ToString( ) %> <%-- Won't work! --%>

<%# DateTime.Now.ToString( ) %> <%-- Work! (Need a call to DataBind in code behind to real show something) --%>

<asp:PlaceHolder runat="server" id="SomeChild">

<%= DateTime.Now.ToString( ) %> <%-- Work!!! Because we modify the control collection of WeDynamicallyAddControlForThisInCodeBehind and not SomeChild! --%>

<%# DateTime.Now.ToString( ) %> <%-- Of course work! --%>

</asp:PlaceHolder>

<%-- Dynamic controls go here --%>

</asp:PlaceHolder>

</asp:PlaceHolder>

Codebehind:

WeDinamicallyAddControlForThisInCodeBehind.Controls.Add( ... ); //or similar to trigger the error in some case see above.


Thank you for pointing out my mistake,I've corrected it,thanks again:)


Hi Jin-Yu Yin,

Thanks for you reply.

I have visited the posts you specified before I created this post Smile All of posts you specified discuss about custom code we write for user controls, images etc. with <% %> tags inside its markup/code and we can resolve this error by updating code as specified in these post.

In my case; I am not adding any of my own user controls or images etc. I am receving error when I am trying to addToolkitScriptManager in the control list.

How can I change code for ToolkitScriptManager to resolve this error? What should I do to addToolkitScriptManagerdynamically in my base page?

Thanks, Vishant


Hi

It not means that the issue come up when you add any of user controls or images to the page.

It means that the issue come up when you add any contorl(inludeToolkitScriptManager) dynamically in thecode-behind to a page or a user contorl and there iscodeblocks like <%= %> at where the contorl add to.

For example:

<contorlA>

<%= %>

</contorlA>

When you try to add <contorlB> to <contorlA> and want to change the code to:

<contorlA>

<%= %>

<contorlB>

</contorlB>

</contorlA>

Then the error comes up,because you cann't modifythecontrolscollection ofthe contorlA as there is a <%= %>codeblocks in it.

As I mentioned in my first reply, You can resolve this issue by change the code to:

<contorlA>

<div><%= %></div>

</contorlA>

Then add contorls to contorlA dynamically without the error.

Good luck!


Hi V,

Usuallly there could be two problems when you try to add a scriptmanager/toolkitscriptmanager to a page dinamically:

a) Adding dynamically the scriptmanager to the page is tricky, because it should be donevery early in the page lifecycle (forget page_load immediatelly for this...)

This is a good thread how to do this:

Re: Is it possible to add a ScriptManager to a page dynamically?

b) The <% %> code block error.

If you follow the instruction from a) you need to eliminate all <%= %> below the form tag, except when <%= %> are in a child asp.net control of the form tag.

Ps:

Yin-Yu-Yin suggest to use this for workaround:

<contorlA>

<div><%= %></div>

</contorlA>

but this won't work!!!

You need aserver side asp.net control around your code block, for example:

<contorlA>

<asp:Panel runat="server"><%= %></asp:Panel>

</contorlA>

this should work...


Exception Problem

Hi...
I've a problem when exceptions are raised using a ASP.NET AJAX framework.

I have a exception raised inside a updatepanel, and its show an alert wrote :
"Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occured while processing the request on the server. The status code returned from the server was: 500."
and this message dont correspond with the real Exception message.

When I used the event "AsyncPostBackError" of ScriptManager, the Exception that received in the e.Exception parameter its the correct exception and message that was raised.


thanks

Hi

for myself, i got this error when something wrong to call web services...(i am not sure you have web services in your call or not)

here is another thread about same issue. have a look

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


Well,

I'm not uses a webservice in this case. The error occur when is raised my personalised Exception (throw new exception("my error")).

Someone have a answer?

Thanks...

Exception has been thrown by the target of an invocation.

I have an Atlas enabled asp page working fine in Visual Web Developer 2005.

It has a Web Service with two methods one for an autocomplete and another to generate a datatable to populate a datagrid.

The second method makes calls two methods from a DataSet object.(one gets a row and the other its details.)

When I deploy to produccion the autocomplete works fine but populating the datagrid fails with:

Exception has been thrown by the target of an invocation

thrown by InternetExplorer.

I tested the Web Service calling its operations directly and it works fine.

Please help.

ps. the production machine has low space in C:\ drive.

In both cases I go against the same SQL Server 2000 database.

Since I posted the question above I was able to "deploy" to a Virtual Directory (called "LocalAtlas" situated on D:\VB Projects\VB Web Developer\Atlas Web Virtual Dir\ ) of my Local IIS and after I added the impersonation tag

<

identityimpersonate="true"userName="vvvvvvvv"password="pppppppp"/>

the page worked as expected. However, it is looking for the .asmx file in the same directory where Visual Studio looks.

But changing the KEY tag from

<

addkey="OBWebServiceRef.OBWebService"value="http://localhost:1459/AtlasWebSite1/OBWebService.asmx"/>

as created by Visual Web Dev to

<

addkey="OBWebServiceRef.OBWebService"value="http://localhost/LocalAtlas/OBWebService.asmx"/>

or anything else I can think of (in Web.config) does not work.

(I removed the fileAtlasWebSite1/OBWebService.asmxto avoid using it)

Example of using ControlBase class

As I've learened from ASP.NET AJAX IN ACTION AJAX toolkit also allow as to create Script Controls (AJAX Extension) with ControlaBase class (Extenders are inherited from ExtenderBase). Why ajax toolkit provide only extender template? Have anybody used ControlBase class?

Hi,

Which ControlBase class are you referring to? There is only a ExtenderControlBase class that acts as the base class.

The main purpose of the template is to provide a better starting point for creating an Extender, some necessary logics has been added in the base class. Of course, you may choose a different base class, event Control class. But developers will have to do more in this case, and it's more error-prone.


Raymond Wen - MSFT:

Which ControlBase class are you referring to?

On the server side, the Ajax Control Toolkit defines two base classes: ExtenderControlBase and ScriptControlBase. The ExtenderControlBase class derives from the ExtenderControl class and is used to create extenders. The ScriptControlBase class inherits from the ScriptControl class and is used to create script controls.

On the client side, the Microsoft Ajax Library provides the Sys.UI.Behavior and Sys.UI.Control classes for creating visual components. In turn, the Toolkit API provides base classes that encapsulate additional functionality for creating behaviors and controls. These classes are called BehaviorBase and ControlBase.

These are two quotations from Manning ASP.NET AJAX IN ACTION

example codes

Hi,

is there anything out there that shows some working examples (codes) of the control toolkit? Nothttp://ajax.asp.net/ajaxtoolkit/, it only lists the properties but does not show how to use them.

Thanks.

Is it safe to assume that there is nothing like a turorial or a document that shows you how to create the controls? I googled for these but didn't find anything.

example "Using the ASP.Net "Atlas" XmlDataSource control" doesnt work!

on :http://atlas.asp.net/docs/atlas/doc/data/default.aspx#XmlDataSource, the "Using the ASP.Net "Atlas" XmlDataSource control" doesn't work.
On click of the link, I redirect it to the http://www.asp.net/forums page.

Can someone help me solving the problem?

Thanks in advace,
Stefano

Stefano,

This appears to work for me. Can you please try it again in a new browser window? Alternatively, you can go tohttp://atlas.asp.net/docs/atlas/doc/data/default.aspxand then scroll down.

Thanks,

Shanku


Sorry, I did not mean to say that the link does not work, but that the example does not work.
If I click "Run it" button in the examples it opens the page: http://atlas.asp.net/docs/atlas/samples/data/XmlDataSource.aspx.
If I click the "Sample Post" link, I redirect to the http://www.asp.net/forums page.

example "Returning a DataTable" doesnt work!

on :http://atlas.asp.net/quickstart/default.aspx, the "Returning a DataTable" doesn't work( on atlas.asp.net. and on my local server too) I don't understand!

Any data are binding!

I'm using IE6! I see somewhere that it's not <binding> but <web:binding> it doesn't work better!

Help me please

ALCINA.

thanks to Garbin. he has provide one nice example in
http://forums.asp.net/1198570/ShowPost.aspx

check it out

events in composite control + gridview + asp.net ajax

Hi,

I'm creating a composite control with gridview and buttons on it. I'm using asp.net ajax toolkit controls in this control. i created a custom image button and added event handler and trying to catch the command in the parent control. I'm using this custom image button in the gridview for selection the row. when i run the control, the control shows the data. Whn i click on the image, the command method is not raised in the parent. When i remove Ajax from the page, then its working. Any help is appreciated.

Thanks

Subba

i figured it out.. i'm using the webcontrol library instead of the ajax control library template for building the composite control. Now it is working.


This issue is still not resolved. The problem is occuring when i use the asp.net toolkit hover control on the gridview. If i remove that hover control then the event is working on the gridview. Can someone help me out..

events for asp controls nested in an atlas control

How do you go about accessing and declaring events for thosecontrols that are nested within the accordion control (for example) ?

ie.I want to have the following Sub for a txtBox that is nested within anaccordionpane? I understand to get to the control's properties you canuse the .FindControls method on the accordion pane, but how do Ideclare a control's event like below?

Protected SubtxtBox_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs)Handles txtBox.TextChanged
...
End Sub

<atlasToolkit:AccordionPane ID="AccordionPane1" runat="server">
<Header><a href="http://links.10026.com/?link=" onclick="return false;"class="accordionLink">5. References</a></Header>
<Content>
<asp:TextBox ID="txtBox" runat="server" CssClass="txtBox" />
</Content>
</atlasToolkit:AccordionPane>

Thanks

You should be able to wire them up like you normally would through either HTML or in code.

via HTML: Just add TextChanged="txtBox_TextChanged" to your TextBox tag.

programmatically: Use FindControls to get the control and then (C#) objTextBoxRef.TextChanged += EventHandler(txtBox_TextChanged);


How would I do it in VB.Net ?

In HTML I have, for example:

<asp:TextBox ID="txtBox" OnTextChanged="txtBox_TextChanged" runat="server" CssClass="txtBox" />

on the .vb code page I then have:

Public WithEvetns txtBox as TextBox

Sub txtBox_TextChanged(ByValsender As Object, ByVal e As System.EventArgs) HandlestxtBox.TextChanged

xtBox.Text = Format(txtBoxy.Text, "currency")

End Sub

But I get the following error:

Error 1 Method 'Sub txtBoxTextChanged()' does not have thesame signature as delegate 'Delegate Sub EventHandler(sender As Object,e As System.EventArgs)'.


excuse my typos...in my last post.Actually my errors window was just not refreshing.

But still, when I run it, the textchanged event does not fire at all...


...nevermind. i did not have the attribute "AutoPostBack = True" in my tag..I hate it when I'm such a beginner...

Wednesday, March 21, 2012

Event Management Project - General Questions

Hello,

I have been given the project of writing a web based Event Management Suite. I have a pretty good knowledge of ASP.NET and C# but would like to use AJAX for this project to elimate postbacks.

Goal:
- To create an interface that allows the user to visually define an actual venue.
- The user would define the size of the grid they need for the Event Location they want to define.
- The user would then be presented with a grid of the size they defined. The default type for each coordinate on the grid the user defined would be Floor.
- A graphic would be inserted into each coordinate on the grid to represent type Floor.
- The user would then be able to define two other types for each location in the grid.
- Seat
- Stage
- The graphic on the designated coordinate would change to reflect the defined type.
- The user would then be able to define the properties for the seats.
- Seat Name (ie A1, B2, C3)

This is only the first part of creating the Event Management Suite. But the Location must be defined before any of the other Event Properties can be defined.

Questions:
1. Is AJAX suited for this task.
2. If so what controls would you advise me to learn about and use.

I'm completely new to AJAX, so the more specific you are with answer and suggestions the better.

Thanks for helping me with this!!

You could accomplish this by utilizing the ASP.NETAjax Control Toolkit and Microsoft AJAX RC1. However, it would probably take a good amount of time to get the positioning of all of your elements/objects just right.

You should look at utlizing the ResizableControl and the DragPanel Control inside of the Ajax Control ToolKit. You might have to create your own control utlizing the DragOverlayExtender Class, and possibly the DragDropManager client side component.

However, even though these controls exist it would probably be easier and take less time if you have Flash experience to develop this kind of system. It provides better control for bounding boxes on dragging, duplicating movie clips and alot of other easy UI functionality. Plus you can then keep everything as far as the data behind the Event Layouts in XML for instance and pass the information to a Web Service that you create which in turn can store it in a database.

Just a few cents from my point of view. Definetely possibly in ASP.NET with ASP.NET Microsoft Ajax, it just will take you a bit of time to make sure the positioning and data behind it all works out.

Good luck,

JoeWeb