Showing posts with label server. Show all posts
Showing posts with label server. Show all posts

Wednesday, March 28, 2012

Page with AJAX controls posts back twice to the server

I have a form containing three AJAX UpdatePanels, two of which contain a pair of listboxes and a pair of buttons, with the third one containing a pair of radio buttons in a radiobutton list and either three CascadingDropDown lists or two CascadingDropDown lists and a textbox depending on which radio button is selected. The only other control on my form is a button to submit the information on the form to the server.

One thing I've noticed is the information gets posted back to the server twice when the button is clicked. This causes a duplicate record to be written to two tables and a SQL exception being thrown when it tries to write a duplicate record to a third table since it violates that table's primary key constraint. At first, I thought the cause might've been due to the submit button being contained in the third UpdatePanel I mentioned, so I removed it from there and placed it by itself ... but the problem still occurs. One other thing I've noticed is that when data for one of the UpdatePanels is to be updated via a postback to the server, the other two UpdatePanels act as if they're also being posted back to the server; in other words, all three panels noticeably flicker simultaneously. I have a sneaking suspicion this may somehow tie into my entire page being posted back twice when the submit button is clicked, but I'm not at all sure.

What can I do to prevent my page from being posted back twice?

Hi,

any sync postback at the server side is almost identical to regual postback including:

- all control values are posted to the server
- Viewstate is transferred to the server and back

The most important difference is in the rendering phass: only update panels are rendered and their content transferred to the client

So, you must design your application in such a way, that removing all update panels will not break server logic. UpdatePanels reduce flickering, but they don't change how server code process data.

-yuriy


I think there a couple things that can cause this... I think ImageButtons can get rendered as "Submit" buttons, and have a __doPostBack call attached to their OnClick, which seems to make a double postback. Also, I think a button has a UseSubmitBehavior property... try setting that to false.

Page_Validators in AJAX.NET problem.

Good day,

Using ASP.NET 2.0 AJAX Extensions 1.0 (1.0.61025) I am getting different output from my dev environment and another Windows 2003 server. It is causing a null reference exception because of the absence of some script, as follows.

A page that demonstrates the problem. Essentially a Textbox with a Validator in an UpdatePanel. The Textbox is hidden in a partial page update and the validator isn't removed from Page_Validators, leading to a null reference exception. Here it is.

1<%@dotnet.itags.org. Page Language="C#" %>
2<html xmlns="http://www.w3.org/1999/xhtml">
3<head>
4<title>AJAX Test</title>
5<script runat="server">
6 protected void Button1_Click(object sender, EventArgs e)
7 {
8 TextBox1.Visible = false;
9 }
10</script>
11</head>
12<body>
13 <form id="form1" runat="server">
14 <div>
15
16 <asp:ScriptManager ID="ScriptManager1" runat="server" />
17 <asp:UpdatePanel ID="UpdatePanel1" runat="server"><ContentTemplate>
18 <asp:TextBox ID="TextBox1" runat="server" />
19 <asp:RequiredFieldValidator ID="req" runat="server" ControlToValidate="TextBox1">Bad!</asp:RequiredFieldValidator>
20 <br />
21 <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" />
22 </ContentTemplate></asp:UpdatePanel>
23
24 </div>
25 </form>
26</body>
27</html>
Here is the output from the dev environment that works:
1<html xmlns="http://www.w3.org/1999/xhtml">
2<head>
3<title>AJAX Test</title>
45</head>
6<body>
7 <form name="form1" method="post" action="ajaxTest.aspx" onsubmit="javascript:return WebForm_OnSubmit();" id="form1">
8<div>
9<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
10<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
11<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTEzMDMxMDUwMDhkZDuvWiPpfDn3oBIdbrlUSDkq1FdR" />
12</div>
1314<script type="text/javascript">
15<!--
16var theForm = document.forms['form1'];
17if (!theForm) {
18 theForm = document.form1;
19}
20function __doPostBack(eventTarget, eventArgument) {
21 if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
22 theForm.__EVENTTARGET.value = eventTarget;
23 theForm.__EVENTARGUMENT.value = eventArgument;
24 theForm.submit();
25 }
26}
27// -->2829</script>
303132<script src="/WebResource.axd?d=aw9IrFUp2_oQ8Owgb8KfHw2&t=633198061661875000" type="text/javascript"></script>
333435<script src="/ScriptResource.axd?d=CKqJO5pnLiMiiKIAPSjUhlVSq_XssPmgCzQ3imV6c-ZI8ou-jtF3g7zNM6zAzFuwj0cj4E-Yc9RTfjMvluxK4g2&t=633198061661875000" type="text/javascript"></script>
36<script src="/ScriptResource.axd?d=cKz-vvqLo1ehaWyVHnXCamccZCS0TLr_WkNiTAu40bnCXSUBzVyHwrKIRYpIqnRFj0bnuLFtFlIG1uLE2IU0HlTdJFkwvyWnrxefUsmR0881&t=633278094321250000" type="text/javascript"></script>
37<script src="/ScriptResource.axd?d=cKz-vvqLo1ehaWyVHnXCamccZCS0TLr_WkNiTAu40bnCXSUBzVyHwrKIRYpIqnRFj0bnuLFtFlIG1uLE2IU0HjrmGHRUhUO2-euEh4H2gbI1&t=633278094321250000" type="text/javascript"></script>
38<script type="text/javascript">
39<!--
40function WebForm_OnSubmit() {
41if (typeof(ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false) return false;
42return true;
43}
44// -->45</script>
4647 <div>
4849 <script type="text/javascript">
50//<![CDATA[51Sys.WebForms.PageRequestManager._initialize('ScriptManager1', document.getElementById('form1'));
52Sys.WebForms.PageRequestManager.getInstance()._updateControls(['tUpdatePanel1'], [], [], 90);
53//]]>
54</script>
5556 <div id="UpdatePanel1">
57
58 <input name="TextBox1" type="text" id="TextBox1" />
59 <span id="req" style="color:Red;visibility:hidden;">Bad!</span>
60 <br />
61 <input type="submit" name="Button1" value="" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("Button1", "", true, "", "", false, false))" id="Button1" />
62
6364</div>
6566 </div>
67
68<script type="text/javascript">
69<!--
70var Page_Validators = new Array(document.getElementById("req"));
71// -->72</script>
7374<script type="text/javascript">
75<!--
76var req = document.all ? document.all["req"] : document.getElementById("req");
77req.controltovalidate = "TextBox1";
78req.evaluationfunction = "RequiredFieldValidatorEvaluateIsValid";
79req.initialvalue = "";
80// -->81</script>
8283<div>
8485<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWAwKV1JT3DQLs0bLrBgKM54rGBh9lq902q1zs4nZQoQSzXWrrFvC2" />
86</div>
8788<script type="text/javascript">
89<!--
90var Page_ValidationActive = false;
91if (typeof(ValidatorOnLoad) == "function") {
92 ValidatorOnLoad();
93}
9495function ValidatorOnSubmit() {
96 if (Page_ValidationActive) {
97 return ValidatorCommonOnSubmit();
98 }
99 else {
100 return true;
101 }
102}
103// -->104</script>
105
106<script type="text/javascript">
107<!--
108Sys.Application.initialize();
109110document.getElementById('req').dispose = function() {
111 Array.remove(Page_Validators, document.getElementById('req'));
112}
113// -->114</script>
115</form>
116</body>
117</html>
118

Here is output from a different server that fails.

1<html xmlns="http://www.w3.org/1999/xhtml">2<head>3<title>AJAX Test</title>45</head>6<body>7 <form name="form1" method="post" action="ajaxTest.aspx" onsubmit="javascript:return WebForm_OnSubmit();" id="form1">8<div>9<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />10<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />11<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTEzMDMxMDUwMDhkZBFseLlnE6oRW+2WytSmHIxuhR3k" />12</div>1314<script type="text/javascript">15<!--16var theForm = document.forms['form1'];17if (!theForm) {18 theForm = document.form1;19}20function __doPostBack(eventTarget, eventArgument) {21 if (!theForm.onsubmit || (theForm.onsubmit() != false)) {22 theForm.__EVENTTARGET.value = eventTarget;23 theForm.__EVENTARGUMENT.value = eventArgument;24 theForm.submit();25 }26}27// -->2829</script>303132<script src="/WebResource.axd?d=y79a8WX0nIrEh3fkGSsX9A2&t=633281399937474336" type="text/javascript"></script>333435<script src="/WebResource.axd?d=w26mxAmgRXp-rT77oPfALL7gzYUT-X6oWLHzd_D6LjY1&t=633281399937474336" type="text/javascript"></script>36<script src="/ScriptResource.axd?d=wZTJCSpVLa8cXWFJgmiuXX-hnAsgClz1-CgGif5xa_-p3CzrOtmsIfh3Y28aQcYFVC5wnr2IJhBHoh2c9Zc0Ch0RynufR4TLZTewW0cBhsc1&t=633281590101841744" type="text/javascript"></script>37<script src="/ScriptResource.axd?d=wZTJCSpVLa8cXWFJgmiuXX-hnAsgClz1-CgGif5xa_-p3CzrOtmsIfh3Y28aQcYFVC5wnr2IJhBHoh2c9Zc0CrgGo9Nt84M88yWLG3iczXI1&t=633281590101841744" type="text/javascript"></script>38<script type="text/javascript">39<!--40function WebForm_OnSubmit() {41if (typeof(ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false) return false;42return true;43}44// -->45</script>4647 <div>4849 <script type="text/javascript">50//<![CDATA[51Sys.WebForms.PageRequestManager._initialize('ScriptManager1', document.getElementById('form1'));52Sys.WebForms.PageRequestManager.getInstance()._updateControls(['tUpdatePanel1'], [], [], 90);53//]]>54</script>5556 <div id="UpdatePanel1">5758 <input name="TextBox1" type="text" id="TextBox1" />59 <span id="req" style="color:Red;visibility:hidden;">Bad!</span>60 <br />61 <input type="submit" name="Button1" value="" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("Button1", "", true, "", "", false, false))" id="Button1" />626364</div>6566 </div>6768<script type="text/javascript">69<!--70var Page_Validators = new Array(document.getElementById("req"));71// -->72</script>7374<script type="text/javascript">75<!--76var req = document.all ? document.all["req"] : document.getElementById("req");77req.controltovalidate = "TextBox1";78req.evaluationfunction = "RequiredFieldValidatorEvaluateIsValid";79req.initialvalue = "";80// -->81</script>8283<div>8485<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWAwKvmrnGBwLs0bLrBgKM54rGBh5nv4YQrwGF0j7OWce2dFyfGsmj" />86</div>8788<script type="text/javascript">89<!--90var Page_ValidationActive = false;91if (typeof(ValidatorOnLoad) == "function") {92 ValidatorOnLoad();93}9495function ValidatorOnSubmit() {96 if (Page_ValidationActive) {97 return ValidatorCommonOnSubmit();98 }99 else {100 return true;101 }102}103// -->104</script>105106<script type="text/javascript">107<!--108Sys.Application.initialize();109// -->110</script>111</form>112</body>113</html>114
The working machine is a dev machine with a long history of messing around.The failing machine is a freshly installed Windows 2003 install with only critical updates, .Net Framework 2.0, Ajax Extensions.I uninstalled and reinstalled Ajax Extensions on the dev machine using the same msi.
I am unable to figure out what is different in the configuration.

Any suggestions would be tremendous!

Thanks,

Craig


Validation controls, which includes theBaseCompareValidator,BaseValidator,CompareValidator,CustomValidator,RangeValidator,RegularExpressionValidator,RequiredFieldValidator, andValidationSummary control are not compatible with UpdatePanel

See it here

http://weblogs.asp.net/scottgu/archive/2007/01/25/links-to-asp-net-ajax-1-0-resources-and-answers-to-some-common-questions.aspx

You can downlaod compatible ersion of validators from here

http://blogs.msdn.com/mattgi/archive/2007/01/23/asp-net-ajax-validators.aspx


Thanks muchly! :)

pagemethod call code sample

Can anyont point me to a code sample where a call is made to a server page method from the client script code?

thanks!

Pratibha

Hi,

please checkthis post from my blog.

pageLoaded event

I have created an ASP.NET custom server control that is updated using AJAX via an UpdatePanel using the Tick event of a Timer control as the asyc trigger. I need to execute javascript each time a partial postback returns so I am using the pageLoaded event. This works perfectly in IE7 but doesn't fire in Firefox 2.0.0.3 or Opera 9. On other browsers it never fires the pageLoaded event, but it does the AJAX updating and other javascript works. I am registering the client code during my control's render method.. I have also tried using the endRequest event. Please help. Why won't it work on other browsers.

Below is the rendered HTML:<!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><title>Untitled Page</title><meta content="text/html;charset=iso-8859-1" http-equiv="content-type" /><meta content="NO-CACHE" http-equiv="PRAGMA" /><meta content="NO-CACHE" http-equiv="CACHE-CONTROL" /><meta content="0" http-equiv="EXPIRES" /><style type='text/css'> a.info:active{z-index:0; position:relative; background-color:#FFF647} a.info label{display: none} a.info:active label{ display:inline; position:absolute; white-space:normal; text-wrap:normal; word-wrap:break-word; left:label.parent.width; top:label.parent.height; width:250px; border:1px solid #91907C; background-color:#EAE7C6; z-index:-1; } </style> </head><body> <form name="form1" method="post" action="Default.aspx" id="form1"><div><input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" /><input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" /><input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTEwMzQxMTA4OTkPZBYCAgMPZBYCAgEPZBYCAgIPZBYCZg9kFgJmDxYGHgtjZWxscGFkZGluZwUBMB4LY2VsbHNwYWNpbmcFATAeBXN0eWxlBSlwYWRkaW5nOjVweDt6LWluZGV4OjIwO3Bvc2l0aW9uOmFic29sdXRlO2RkMUSTfpjSwghJETl9/Jgkha9oZaA=" /></div><script type="text/javascript"><!--var theForm = document.forms['form1'];if (!theForm) { theForm = document.form1;}function __doPostBack(eventTarget, eventArgument) { if (!theForm.onsubmit || (theForm.onsubmit() != false)) { theForm.__EVENTTARGET.value = eventTarget; theForm.__EVENTARGUMENT.value = eventArgument; theForm.submit(); }}// --></script><script src="/WebResource.axd?d=9DvoInn8tlftzCiBPvQagg2&t=632974035101093750" type="text/javascript"></script><script src="/ScriptResource.axd?d=WAnysv6JNp-Tgl_8AndGJnGXdfOUUPdccvGwkhkSJu2uP8RLi_go1jCrdTe0jCpJF0u8GYhfCflHcjQdOJTaXMeB6qn3C9aitPrPuScmgSM1&t=633063657262888841" type="text/javascript"></script><script src="/ScriptResource.axd?d=WAnysv6JNp-Tgl_8AndGJnGXdfOUUPdccvGwkhkSJu2uP8RLi_go1jCrdTe0jCpJF0u8GYhfCflHcjQdOJTaXOmCYkHGf_k8diSD9UcMEoc1&t=633063657262888841" type="text/javascript"></script><script src="/ScriptResource.axd?d=WAnysv6JNp-Tgl_8AndGJnGXdfOUUPdccvGwkhkSJu2uP8RLi_go1jCrdTe0jCpJF0u8GYhfCflHcjQdOJTaXLsHgXZk2LxHv8oSN-rIGKs1&t=633063657262888841" type="text/javascript"></script> <span id="events" style="font-size:Small;"><span id="events_timer1" style="visibility:hidden;display:none;"></span><input name="events$ctl00" type="hidden" id="events_ctl00" /><div id="events_UpdatePanel1"><table cellpadding="0" cellspacing="0" style="padding:5px;z-index:20;position:absolute;"><tr><td rowspan="2" style="border-bottom-style:None;border-bottom-color:#91907C;border-bottom-width:thin;padding-bottom:5px;padding-top:5px;"><img src="../images/greenshd.gif" alt="The IT Road Show.........................." /></td><td style="padding-left:5px;">Tuesday 24 Apr</td><td style="padding-left:15px;">3:30 pm</td></tr><tr><td colspan="2" style="border-bottom-style:None;border-bottom-color:#91907C;border-bottom-width:thin;padding-left:5px;padding-bottom:5px;"><a href="http://www.nova100.com.au" id="events_3160" EventsEventDatesId="3160" LabelId="events_label_0_3160" onfocus="document.getElementById('events_ctl00').value = this.LabelId" onblur="document.getElementById('events_ctl00').value = ''" class="info">The IT Road Show.......................... </a></td></tr><tr><td rowspan="2" style="border-bottom-style:None;border-bottom-color:#91907C;border-bottom-width:thin;padding-bottom:5px;padding-top:5px;"><img src="../images/AKMAL_OVER.gif" alt="The Akmal Show" /></td><td style="padding-left:5px;">Tuesday 24 Apr</td><td style="padding-left:15px;">4:00 pm</td></tr><tr><td colspan="2" style="border-bottom-style:None;border-bottom-color:#91907C;border-bottom-width:thin;padding-left:5px;padding-bottom:5px;"><a href="#" id="events_2749" EventsEventDatesId="2749" LabelId="events_label_1_2749" onfocus="document.getElementById('events_ctl00').value = this.LabelId" onblur="document.getElementById('events_ctl00').value = ''" class="info">The Akmal Show <label id="events_label_1_2749" style="text-decoration:none;">The Akmal Show with Kate Richie Weekdays 4pm-6pm.Akmal was born in Egypt - then moved to Australia. Akmal's mum doesn't think he's that funny - now the rest of Australia think he's ha haa hilarious.</label></a></td></tr><tr><td rowspan="2" style="border-bottom-style:None;border-bottom-color:#91907C;border-bottom-width:thin;padding-bottom:5px;padding-top:5px;"><img src="../images/greenshd.gif" alt="The IT Road Show.........................." /></td><td style="padding-left:5px;">Wednesday 25 Apr</td><td style="padding-left:15px;">3:30 pm</td></tr><tr><td colspan="2" style="border-bottom-style:None;border-bottom-color:#91907C;border-bottom-width:thin;padding-left:5px;padding-bottom:5px;"><a href="http://www.nova100.com.au" id="events_3161" EventsEventDatesId="3161" LabelId="events_label_2_3161" onfocus="document.getElementById('events_ctl00').value = this.LabelId" onblur="document.getElementById('events_ctl00').value = ''" class="info">The IT Road Show.......................... </a></td></tr><tr><td rowspan="2" style="border-bottom-style:None;border-bottom-color:#91907C;border-bottom-width:thin;padding-bottom:5px;padding-top:5px;"><img src="../images/AKMAL_OVER.gif" alt="The Akmal Show" /></td><td style="padding-left:5px;">Wednesday 25 Apr</td><td style="padding-left:15px;">4:00 pm</td></tr><tr><td colspan="2" style="border-bottom-style:None;border-bottom-color:#91907C;border-bottom-width:thin;padding-left:5px;padding-bottom:5px;"><a href="#" id="events_2750" EventsEventDatesId="2750" LabelId="events_label_3_2750" onfocus="document.getElementById('events_ctl00').value = this.LabelId" onblur="document.getElementById('events_ctl00').value = ''" class="info">The Akmal Show <label id="events_label_3_2750" style="text-decoration:none;">The Akmal Show with Kate Richie Weekdays 4pm-6pm.Akmal was born in Egypt - then moved to Australia. Akmal's mum doesn't think he's that funny - now the rest of Australia think he's ha haa hilarious.</label></a></td></tr><tr><td rowspan="2" style="padding-bottom:5px;padding-top:5px;"><img src="../images/redshd.gif" alt="test add 25" /></td><td style="padding-left:5px;">Thursday 26 Apr</td><td style="padding-left:15px;">2:29 pm</td></tr><tr><td colspan="2" style="padding-left:5px;padding-bottom:5px;"><a href="k" id="events_136" EventsEventDatesId="136" LabelId="events_label_4_136" onfocus="document.getElementById('events_ctl00').value = this.LabelId" onblur="document.getElementById('events_ctl00').value = ''" class="info">test add 25 </a></td></tr></table></div></span> <script type="text/javascript">//<![CDATA[Sys.WebForms.PageRequestManager._initialize('ctl06', document.getElementById('form1'));Sys.WebForms.PageRequestManager.getInstance()._updateControls(['tevents$UpdatePanel1'], ['events','events$timer1'], [], 90);//]]></script><script type="text/javascript"><!--Sys.Application.add_init(function() { $create(Sys.UI._Timer, {"enabled":true,"interval":1000,"uniqueID":"events$timer1"}, null, null, $get("events_timer1"));}); Type.registerNamespace('EventsManager'); var prm = Sys.WebForms.PageRequestManager.getInstance(); if (prm != null) { prm.add_endRequest(pageLoadedHandler); } function window.onload() { } function pageLoadedHandler(sender, args) { var hidden = document.getElementById('events_ctl00'); if (hidden != null) { var labelId = hidden.value; if (labelId.length > 0) { var lbl = document.getElementById(labelId); if (lbl != null) { lbl.parentElement.setActive(); } } } } Sys.Application.initialize();// --></script></form> </body></html>

Below is my code for the Render method when I used the endRequest event:

protected override void Render(HtmlTextWriter writer) {base.Render(writer);//Add script and register it. Page.ClientScript.RegisterStartupScript(typeof(EventsManager),"script", @dotnet.itags.org." Type.registerNamespace('EventsManager'); var prm = Sys.WebForms.PageRequestManager.getInstance(); if (prm != null) { prm.add_endRequest(pageLoadedHandler); } function window.onload() { } function pageLoadedHandler(sender, args) { var hidden = document.getElementById('" + ClickedLinkLabelId.ClientID + @dotnet.itags.org."'); if (hidden != null) { var labelId = hidden.value; if (labelId.length > 0) { var lbl = document.getElementById(labelId); if (lbl != null) { lbl.parentElement.setActive(); } } } } ",true); }

Hi,

Can you show me a stripped version of your control and a sample page using it?

It will be easier for us to trouble shooting. Thanks.


Hi Raymond,

I really appreciate your offer of help, but I just figured out what the problem was.

My javascript code below was causing a problem for all the code in my script block on all browsers apart from IE.

Problem code:

function window.onload()
{

}

When I changed it to the code below, it worked in all browsers.

Correct code:

window.onload = function()
{
document.getElementById('" + TimeZoneOffset.ClientID + @."').value = -(new Date().getTimezoneOffset());
}

Thanks again.

PageMethods dont regenerate on file change?

If I define a new page method or change an existing page method I have to restart my dev asp.net server to see the change in the generated javascript (page prototype)? anyone else having this problem?

thanks

Hi,

Without any valuable information, it is hard to say where the problem lies on.

Please provide any more information,eg. any code of this.

Thanks!


Hi Craigw,

It seems like a cache issue rather than a IIS issue. So I suggest you to save your web.config file without any modifications and have a test. If it works, we can confirm it.

Also you can delete all the cache file or do the following steps. open the IE -->Tools-->Internet Options-->General Dialog-->Browswer History-->Settings-->select "Every time I visit the webpage".

I hope this help. If it doesn't work, please feel free to let me know with more information.

Best regards,

Jonathan


This problem has been quite annoying for some time. Can you please confirm if it has been identified and whether a fix will be available?

It happens on the server (Win 2003 R2) as well as on developer PCs (Cassini). Restarting the web server does the trick as well as re-saving web.config. It's quite easy to reproduce (and yes, I have enbaled PageMethods in the ScriptService tag...)

Monday, March 26, 2012

PageMethods is undefined

Hi there

I have a simple page that calls a server side page method via the scriptmanager / page methods detailed on this site. This has worked fine recently when until I updated our dev team to use the new asp.net ajax 1.0.

Once I'd updated my web.config as per the doco all works fine on my pc but on all others when I call the server side method I get the client script error " PageMethods Is 'Undefined' ". I am sure this is an environmental issue but I would appreciate any tips on how to figure out what is going on!

To update one of the boxes (eg our test server) I did the following steps.

    Uninstall previous ASP.net Ajax (RC1)Install new versionUpdate web.config as per instructions in the doco

Here is my source code

<%@dotnet.itags.org. Page Language="C#" AutoEventWireup="true" CodeFile="AddNote.aspx.cs" Inherits="controls_AddNote" EnableViewState="true" %><%@dotnet.itags.org. Import Namespace="System.Web.Services" %><!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>Add a note to this cell</title> <link rel="stylesheet" type="text/css" href="../css/calumo default.css" /> </head> <body leftmargin="0" rightmargin="0" topmargin="0" bottommargin="0"> <script type="text/javascript" language="javascript"> function PageMethodCall() { var TicketId=parseInt($get("inpTicketId").value); var DataSource=$get("inpDataSrc").value; var Catalog=$get("inpCatalog").value; var Cube=$get("inpCube").value; var DataPointMdx=$get("inpMdx").value; var NoteValue=$get("taNote").value; if(NoteValue.length>0) PageMethods.SendNote(TicketId,DataSource,Catalog,Cube,DataPointMdx,NoteValue,OnSucceeded); } // This is the callback function // that process the page method call // return value. function OnSucceeded(result) { // Display the result. if(result==1) window.close(); else alert("Calumo Server Exception:-" + result); } function Validate() { if($get("taNote").innerText.length>0) $get("btnSend").value="Send"; else $get("btnSend").value="Close"; } </script> <form id="frmAddNote" runat="server" target="_self"><asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager> <input runat="server" type="hidden" id="inpTicketId" value="" /> <input runat="server" type="hidden" id="inpDataSrc" value="" /> <input runat="server" type="hidden" id="inpCatalog" value="" /> <input runat="server" type="hidden" id="inpCube" value="" /> <input runat="server" type="hidden" id="inpMdx" value="" /> <table id="Table1" runat="server" height="100%" width="95%" cellpadding="0" cellspacing="0"> <tr id="trHeader" > <td><img alt="" src="../images/Calumo/top_bar.jpg"/></td> </tr> <tr><td> </td></tr> <tr id="trBody"> <td id="tdNoteArea" align="center">  <textarea cols="10" runat="server" style="height:100%;width:650px;" id="taNote" rows="10" ></textarea> </td> </tr> <tr><td> </td></tr> <tr id="trFooter"> <td style="padding-right:20px;width:100%" id="tdClose" align="right"> <input id="btnSend" type="button" value="Send" onclick="javascript:PageMethodCall();" /> </td> </tr> </table> </form> </body></html>

and here is the server code

 [WebMethod()]public static string SendNote(int TicketId,string DataSource,string Catalog,string Cube,string DataPointMdx,string NoteValue) {try {// Add a note to the server code and return a sample msgreturn"It Works"; }catch(Exception ex) {return ex.Message; } }

Any hints on troubleshooting would be greatly appreciated

Thanks in advance

Graham

Try settingEnablePageMethods="true"

<

asp:ScriptManagerID="ScriptManager1"runat="server"EnablePageMethods="true">

Yep thats it! Would probably be a good idea to add to the update doco

thanks


Was that missing in the documentation somewhere? We'll happily fix it... just point me to where it's missing.


There should probably be a section on Page Methods...in the docs that is accessible by the left hand side index..

Also, for whatever reason - the UpdatePanels UpdateMode is set by default to "Always" a special highlight in the docs should indicate this is the default and to change it to conditional for partial rendering / asynchronous updates. I was kinda surprised when investigating some of the post and issues on always full postbacks - that when I just dragged and dropped an updatepanel in designer - it defaulted to "Always"... kinda missing the purpose I think as if you are releasing this - then the default should err on side of the Ajax technology it is supposed to provide and this is a change I think from the RCs but not positive as I always declare everything anyways... but alot of folks just drag and drop and assume they are getting the settings for exploiting the Ajax enviroment...


I followed this docohttp://ajax.asp.net/documentation/Migration_Guide_RC_to_RTM.aspx

and unless I skipped over it I didn't find any reference to the EnablePageMethods

thanks again


I agree! Where can you find reference and documentation to PageMethods ? I use the block of code on this post as my reference right now ..


http://ajax.asp.net/docs/tutorials/ExposingWebServicesToAJAXTutorial.aspx

I agree this would be nice to see in the "differences" docs. I'll see if it can be added.


Just wanted to say thanks, all.

I was trying to get a method to run from a page (both in the .aspx file and in the code behind) and kept getting the js error of "PageMethods" not found. Adding that attribute to the ScriptManager cured the problem.

Pete.

PageMethods quirk

So here's what I found while using PageMethods in Beta 2

    A server side method needs the attribute [System.Web.Services.WebMethod]A server side method should be static or else you'll get a PageMethods is undefined errorA server side method should NOT be defined in code behind but should be in the ASPX page in <script runat="server"> tag.Here's the quirk. A server side method CANNOT have two parameters with names that differ only in the case of their letters. eg. someParam and SomeParam, even if they are of different types, e.g. string and int This will result in a Sys.ArgumentTypeException with the message Object of type Number cannot be converted to type Function. Parameter name OnSuccess.
    <script runat="server"> [System.Web.Services.WebMethod] public static string SomeMethod(string someParam, int SomeParam) { return "Hello " + someParam + " you are " + SomeParam.ToString() + " years old"; } </script>
    <script type="text/javascript" language="javascript"> function CallMethod() { var age = 28; PageMethods.SomeMethod('MyName',age, OnCallResponse); } function OnCallResponse(arg) { alert(arg); } </script>
    Change the SomeParam to age and it will work.

So my question is : Is this a bug, quirk or by design? If a bug or quirk will it be fixed? Sure one NEVER names two parameters the same with just a change in the case but then again, NEVER say NEVER.

Thanks

I SO MUCH SUPPORT your finding #3. It's so stupid that the server side code won't work in code-behind but inline code would work. What the heck?

To any MSFT moderator:

Is there any workaround for #3? This is driving me crazy.


Weird, but I just tried to create a page just like yours and it works even if the static method is in the code behind...

This is the class:

public partialclass _Default : System.Web.UI.Page { [WebMethod]public static string GetServerDate() {return DateTime.Now.ToString(); }}


And this is the ASPX:

<%@. Page Language="C#" AutoEventWireup="true" CodeFile="~/Default.aspx.cs" Inherits="_Default" %><%@. Importnamespace="System.Web.Services"%>"-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html xmlns="http://www.w3.org/1999/xhtml">Untitled Page"server"> "form1" runat="server" method="post"> "ScriptManager1" runat="server" />

"button"value="get date" onclick="GetDate();" id="Button1" />

"date" />

"text/javascript">function GetDate(){ var div = document.getElementById("date"); PageMethods.GetServerDate(function (result) { div.innerText = result; });}

Sorry about my last post which is unreadable...Angel

Reposted:

Weird, but I just tried to create a page just like yours and it works even if the static method is in the code behind...

This is the class:

public partialclass _Default : System.Web.UI.Page
{
[WebMethod]
public static string GetServerDate()
{
return DateTime.Now.ToString();
}
}


And this is the ASPX:

<%@. Page Language="C#" AutoEventWireup="true" CodeFile="~/Default.aspx.cs" Inherits="_Default" %><%@. Import namespace="System.Web.Services"%><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title>Untitled Page</title></head><body> <form id="form1" runat="server" method="post"> <asp:ScriptManager ID="ScriptManager1" runat="server" /> <div> <input type="button" value="get date" onclick="GetDate();" id="Button1" /> <div id="date" /> </div> </form> </body></html><script type="text/javascript">function GetDate(){ var div = document.getElementById("date"); PageMethods.GetServerDate(function (result) { div.innerText = result; });}</script>

This looks a bug, thanks for reporting this issue, and it will be fixed in a future build.
-Hao


Hi,

that is not a bug. Remember that vbscript is case unsensitive.


Hi,

I tried the approach of using static methods for PageMethods in AJAX v1.0 Beta 2, but it is not working. The only change that happened is that the error message has changed from "PageMethods is undefined" to "PageMethods is null or not a object.

PLEASE HELP !!!!


Advance,

Where the heck is "vbscript" in whole picture? We are trying to access a WebMethod from Javascript using MS Ajax Beta 2 in the code-behind file.


I was hoping this would have been corrected in Beta 2. I guess I'll keep using the ATLAS CTP until this is resolved. Oh well, maybe in build 3??


hello.,

this is correct. the problem is related with the EnsureParameters of the WebServiceMethodData class. I don't know why, but it's "eating parameters" when they have the same name and differ only in case. here's the "bad" code:

privatevoidEnsureParameters()
{
if (this._parameterData ==null)
{
lock (this)
{
Dictionary<string,WebServiceParameterData>dictionary1 =newDictionary<string,WebServiceParameterData>(StringComparer.OrdinalIgnoreCase);
intnum1 =0;
foreach (ParameterInfoinfo1inthis._methodInfo.GetParameters())
{
dictionary1[info1.Name] =newWebServiceParameterData(info1,num1);
num1++;
}
this._parameterData =dictionary1;
}
}
}
 
I've tried reproducing this with a simple method and i get the 2 parameters and if i add them to a dictionary, i get 2 entries. this is not happening here (yes, i've used reeflection to reproduce what's going on and i can say that the dic only has one parameter.
if anyone have an idea on why is that, please,share with us!
thanks. 


hi.

dom't you hate it when you spend 1 hour looking at code and writing reflection just to see that the damn thing is right in front of you?:

newDictionary<string,WebServiceParameterData>(StringComparer.OrdinalIgnoreCase);
thanks Garbin!
 
 

Yeah, there are two places in the code that are using OrdinalIgnoreCase comparers which is what's causing the problem, removing the IgnoreCase for both dictionaries fixes the problem.

Hope that helps,
-Hao


hello.

does that mena that it'll be removed in the next release?


Yes I've already fixed it in the codebase.

Hope that helps,
-Hao

PageMethods or WebServices ..

I need to recover some server-info from JavaScript (ansynchroniously) so I need any exposed method on the server that could be called from the client. I've seen that there are 2 ways to do this (without using, the easy-fashion UpdatePanel):

WebService

PageMethods

I just don't know what to choose. Most solutions I've seen around the .net community are based upon the use of WebServices but I think that exposing a WebService may cause a lack of security (anyway, I dont know if it's possible to forbid access to the .amsnx file directly from the browser).

Thankyou!

nach_:

I dont know if it's possible to forbid access to the .amsnx file directly from the browser.

It isn't. When using webservices it is the browser which is accessing the the webservice, so forbidding it would prevent the method from working. You could make the webservice call inject a special header in the HTTP request, and check for its existence on the server, but that's about it (well, you could create a more advanced security system, but that also means more overhead).

Webservices are (a lot) less resource hungry than PageMethods, since PageMethods bring along the viewstate and basically instantiate everything on the page as if there was a regular postback in action. PageMethods should only be used if the state of the page is relevant in the call.


Thankyou for your answer gunteman!

The first thing is clear, if you forbid access to .amsnx then nothing will work, great.

What I don't understand is why WebServices are less resource hungry than PageMethods. Far as I know, PageMethods only allow static methods to be exposed so I don't understand why the state of the page may be relevant in that cases (hope I've explained).

Thankyou again!


Whoa! It seems PageMethods have changed since I abandoned them (they used to be non-static and heavy as hell).

Well, then it seems the most logical argument for using webservices is re-use, if the method is to be used from several pages.


That's what I thought but if not reuse is needed then maybe the good option is to use PageMethods (at least are less accessible for possible leechers than webservices, or not)?

Thankyou again!


You could definitely use PageMethods, but bear in mind that they are just as leechable as webservices. The calling mechanism is (now) basically the same as when using webservices. However, if you use some kind of login on your website, the PageMethods will be protected from non-authenticated users (or however you define your security). The same is true for webservices if so defined.

PageRequestManager : Whats the difference between doPostBack and _doCallBack ?

I want some parts of my web page refresh after a focus or changed event being made on a TextBox. What I want to acheive is get back to the server to do some code. I check the PageRequestManager and saw to way to make a postback to the server. What I want to do is get back to the server like I put a submit button without the whole page refresh. Some advices on that would be really appreciate !

It's not overly clear what your trying to do. Are you currently using UpdatePanels? If not, look into them:

http://www.asp.net/ajax/documentation/live/overview/UpdatePanelOverview.aspx

http://www.asp.net/learn/ajax-videos/video-78.aspx

http://www.asp.net/learn/ajax-videos/video-159.aspx


I know it's not clear. I'm sorry. I'll try to explain more clearly.

On a client event like OnFocus or OnBlur or OnChange, I'll check some client state for the input (TextBox) and take decision if I need to get back to the server to refresh some part of my menu. I try to implement a sort of contextual menu. So, when some part (say inside panel1) got focus, I want to make an ajax request to add some stuff to the menu. When the panel lost focus, maybe I'll switch the visibiliy of some parts of the menu on the client side or got back to the server to do some job.

I'm building a sort of UIManager. This Manager need to check some client state(hidden field) and decide to get back to server if I doesn't have all the state it need to add some part of the menu for the contextual part.

So, I put the menu inside and UpdatePanel UpdateMode=Always. When a control (maybe TextBox, RadioButton or panel) got focus, maybe I need to get back to the server. I want to know if it's necessary to put the control inside and Update Panel or I can write some code to submit the form and use eventArgument to know what I have to do...

I hope is it a little be more clear. I appreciate a lot the time you take to help me !


Hi,

Thank you for your post!

Based on my understanding, you just want to refresh the updatepanel via javascript(e.g On a client event like OnFocus or OnBlur or OnChange).

Check out like this:

use __doPostBack to refresh the UpdatePanel

If you have further questions,let me know.

Best Regards,


Hi,

Thank you for this great anwser. It's really what I was searching.

I have another question. I need a way to pass parameter from the client to know what to do when the page refresh on the server. For example, when the TextChanged occured on the TextBox1, I want to update some parts of the menu. Is it a good approach to pass parameter on the EventArguments of the __doPostback ? And which format do you recommand I use ? Or can you recommand me another way of doing that ?

function TextChanged(){ __doPostBack('ClientAjaxComm','');}
Thanks!

Hi,

It is a good approach to pass parameter on the EventArguments of the __doPostback.

Or you can store something into something hiddenfield,and get them at the server side.

It is up to you to which approach you use.

Thanks!

pagerequest manager events seems to be raised to many times by the browser

Hello,

I have the next issue in my web application.

On server i'm sending to the client during a server event with registerdataitem a string -an url.

On client in pageloading i'm getting the url and showing into a popup window. This is the code:

var

wind=null;

var

currenturl=null;

var

i=0;

Sys.Application.add_load(ApplicationLoadHandler);

function

ApplicationLoadHandler(sender, args)

{

//Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);

Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(pageLoadingHandler)

}

//function EndRequestHandler(sender, args)

function

pageLoadingHandler(sender, args)

{

var dataItems = args.get_dataItems();

wind=document.getElementById(

'popupid');if (wind!=null)return;if (document.title.indexOf("Print")>=0)

currenturl=dataItems[

'ctl00_currenturl'];else

currenturl=dataItems[

'currenturl']if (currenturl !=null )//show the popup

{

wind=window.open(currenturl,

'popupid');

//DeleteFile(dataItems['currenturl']);works fine only on ie this solution

}

}

The problem is that the ajax pagerequestmanager event is raised too many times making the popup to be created to many time and sometimes browser to run out of resources.

How could i fix it i mean the pagerequestmanager event to be raised normaly i mean once.

I 'm using ie 6.5

Thanks

Hi,

Please use try this code snippet:

Sys.Application.add_load(ApplicationLoadHandler)

function ApplicationLoadHandler(sender, args)
{
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (!prm.get_isInAsyncPostBack())
{
prm.add_pageLoading(pageLoadingHandler);
}
}

Hope this helps.

PageRequestManagerParserErrorException

PageRequestManagerParserErrorException - The Message recevied from the server could not be parsed...

I'm using asp.net 2.0 with ajax.

I'm getting that error on page that have updatepanel. the page include master page.

I'm not using Response.Write,Output Caching,Response Filters, HttpMoudle, Server.Transfer

also i add the following attributes

enabeEventValidation="false"Trace="false"ValidateRequest="false" to the page.

the error Occur on some client mechine, after i publish my web site.

it is not occur on my mechine.

what else can I do?

Have you taken a look at this blog?http://weblogs.asp.net/leftslipper/archive/2007/02/26/sys-webforms-pagerequestmanagerparsererrorexception-what-it-is-and-how-to-avoid-it.aspx. There is also this blog,http://alpascual.com/blog/al/archive/2007/04/26/How-to-fix-Sys.WebForms.PageRequestManagerParserErrorException-in-AJAX.aspx with this comment by Don Ebert:

"FYI I had the same issue and did everything nothing worked. Then I un-checked REMOVE UNKNOWN HEADERS via the firewall and bang, everything worked. It's possible every1 is looking into it to much. "

-Damien


Thanks a lot. Its Ok now.


Glad you got it working, please mark my last post as the answer if it helped you.

-Damien

PageRequestManagerParserErrorException with the New ASP.Net Ajax framework

I have two simple web pages with two update panels in them. The first one calls the second one using Server.Tranfer or Server.Execute and it gives the following error message:

Sys.WebForms.PageRequestmanagerParsererrorException: The Message received from the Server could not be Parsed. Common caused for this error are when the response is modified by calls to response.Write(), response filters, HttpModules, or server trace is enabled.

Now, this never happened with the previous framework, atlas. I've tried all possible solutions I could think of, but none worked so far.

Try to take a look at the following forums for?reference.
http://forums.asp.net/thread/1467462.aspx
Wish this can help you.

PageRequestManagerServerErrorException

I have a web application built using ASP.NET Ajax 1.0. And now, I have a problem because when the IIS Server is restarted or not available the ajax engine display a message box with PageRequestManagerServerErrorException (Error 500). I would like to know if is possible treat this message and display a friendly message to user. How can I do this?I'm having the same error message pop up randomly after a page has been open for a while. I'm beginning to wonder if it is caused by Session going out of scope. With ASP.NET AJAX 1.0, do AJAX requests within an UpdatePanel moved the Session sliding expiration at all?

Hi,

This exception is thrown at the server. While in an async postback the normal exception/debug chain of the ASP.NET pipeline is ignored by default. You can either enable the normal custom error stuff in web.config by setting ScriptManager.AllowCustomErrorsRedirect on the current script manager to true, or you can handle the exception yourself at the server side by hooking to the AsyncPostBackError event on the script manager, or (if you just want to replace the message sent to the client and no more) you can set the AsyncPostBackErrorMessage.

Since async postbacks will still run through the session module at AcquireRequestState time, it seems unlikely that your sliding expiration interval is not updated. However, if you don't post back for a long period, your session will of course be abandoned. But this will not cause an exception, but rather just start a new session ...

-- Henkk


I found the problem, sorry I forgot to post it.

This error always occurred after a complete postback. I switched the postback out for an async postback, and the errors went away. Basically what was happening was that the user would sometimes be able to click on a control that would trigger an async postback before the entire page was rendered by the browser. This would break the AJAX scripts and throw that error message.

Thank you for the help with the custom errors, though!


I found what the error was. Apparently it always occurred after a regular postback so I was able to track it down. Users were sometimes able to click on a control that fired off an async postback before the entire page was able to load. This would break the AJAX scripts and throw the error.

Thanks for the help with the custom error messages!


Hello!!I have a page that has a textbox, a dropdownlist, a second textbox inside an update panel, and a second updatepanel with final textbox in it. I also have a calculate button

I am entering a number in first textbox and change selection in dropdownlist. It does an async postback with selectedIndexchanges and populates the second text box. Now when I press a calculate button the textbox in second update panel is supposed to return with values.

Both update panels are updatemode = conditional. First one is fired on selectedindexchanged of the dropdownlist and second on click of calculate button.

Everything works the first time. As soon as I calculate once, any subsequent calls to calculate or changing of the dropdown list gives the above error with server code = 500

How should I go about it?


In the calculate method, is there a control being updated that is NOT within the triggered UpdatePanel? That could be causing the issue.

Saturday, March 24, 2012

PageRequestManagerServerErrorException: 404 ??

I have a error when I use Server.Transfer and ASP.NET AJAX.

STEPS:

1- navigate to a page containing a UpdatePanel using SERVER.TRANSFER
2- (first) async call works fine

3 - click again to make second async call and somehow the page path becomes
invalid; the page name is correct but the path seems to belong to the
referer!! (Consequently a 404 server response is returned by the server. see
attached error message )

Anyone help-me?

Server.Transfer really doesn't work well with ASP.NET AJAX. A few people have done some complicated stuff to get it to work, but I recommend just avoiding it altogether if possible. Search around here on the forums, and you can probably find some older discussions of this.

PageRequestManagerServerErrorException: 401

I wrote some server code that work fine in VWD 2008 Express Edition. When I uploaded the page to my site (including the dll that my code uses), I get the following error:

Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occured while processing the request on the server. The status code returned by the server was: 401. How can I find out where the problem is comming from?

Thanks,
Yoni

Server Error 401 is an "Unauthorized" error.


And how can I find out which peace of code is giving me this error?

Thanks,
Yoni


It's probably going to be something where it is trying to access a page, database, etc. that it doesn't have permissions to. I would set breakpoints and just see how far the code is getting.


Thats a problem. As I said, the page and code work fine on my computer - only when I move it to my site I get an error. How do I insert breakpoints? Do you mean I should use "return" statements in diff places until I find where the error originates?

Thanks,
Yoni


On the server you couldn't use breakpoints. I personally am a fan of just putting an extra blank <asp:Label> on the page and writing things to it to see values and my progress. Place occasional "I got to ____ function" statements in the label's text.


I wouldlove to do that: I have tried it, but it doesn't work. My server code takes about 10 seconds - 5 minutes to run and during that time I can't post nothing to the page... I asked how to do this in another forum, but I was given extremely complicated ways of doing this, that I could not do. Do you know how I can change a label while my server code is running?


Hi,

Thank you for your post!

Check out the following link:

http://blogs.msdn.com/david.wang/archive/2005/07/14/HOWTO_Diagnose_IIS_401_Access_Denied.aspx, David Wang said in this article:

One of the most common questions asked about IIS on the newsgroups as well as Microsoft Product Support is "why am I getting 401 Access Denied"?

There are many, many possible causes and variations, but from the IIS perspective, the top-level, logical categories are fixed. This information can help dramatically narrow down the scope of any investigation, but unfortunately, few people know to take advantage of this information. This is what I am going to address with this entry - how to use and diagnose the 401.x error codes on IIS.

Step 1: Determine the SubStatus Code

Step 2: Determine Course of Action

401.1 Denied by Invalid User Credentials

401.2 Denied by Server Configuration

401.3 Denied by Resource ACL

401.4 Denied by Custom ISAPI Filter

401.5 Denied by Custom ISAPI/CGI Web Application

Conclusion

401.1 through 401.3 errors are associated with IIS request processing and allow the logical interpretations and assumptions that I listed above.

Meanwhile, the 401.4 and 401.5 errors are the most arbitrary to diagnose since custom ISAPI DLLs and CGI EXE can cause IIS to behave in non-obvious manners. Thus, much of the logical assumptions about 401.x do not apply.

I hope that this information has been useful in deciphering theh 401.x errors from IIS. If you have additional questions, feel free to post a comment or post a private question via the "contact" link.

Recently, we have also released a tool,AuthDiag, to help troubleshoot IIS access denied issues. You can download it fromthis location. In particular, it has a feature to hook in to various failure points in IIS and directly troubleshoot what is failing on a given request - you need to see and try it out!

If you have further questions, let me know.

Best Regards,

Paging in GridView gets Object Expected Error

I have a grid in an update panel that gets databound at runtime (to index server results). I have implemented paging and it works without atlas. As soon as I place that grid in update panel, paging stops working. All I get is a javascript error saying "line 1 :Object Requiered".

I have tried debugging it but on paging, it doesn't event get to the server.

thanks

Hi Biren,

Have you tried this with the April CTP of Atlas that was released earlier this week?

If it's still a problem, can you please provide some more details on your scenario so that we can investigate?

Thanks,

Eilon


I have done it and it works for me. Object required is a pretty generic error just as the "Object reference not set to an..." in .Net. It could be because of wrong syntax in javascript or html that you might have on the page.

If you don't mind pasting the code on the forum please do so we can look at it.


Just tried it and same error.

here is the code:

<%@. Page Language="VB" AutoEventWireup="false" CodeFile="Index.aspx.vb" Inherits="Index" %>

<!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>Search</title>
<link href="http://links.10026.com/?link=Style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<atlas:ScriptManager EnablePartialRendering="true" ID="atlas1" runat="server" EnableViewState="true" />
<form id="frm1" runat="server">

<atlas:UpdateProgress ID="up11" runat="server" >
<ProgressTemplate >
<table>
<tr>
<th style="color:red">Please wait while your serach results are calculated...</th>
</tr>
<tr>
<td>
<img src="http://pics.10026.com/?src=images/spinner.gif" /></td>
</tr>
</table>

</ProgressTemplate>
</atlas:UpdateProgress>
<atlas:UpdatePanel ID="up1" Mode="conditional" runat="server" >
<ContentTemplate >



<table>
<tr>
<th>A word or phrase in the file: </th><td><asp:TextBox ID="txtsearch" runat="server" /></td>
</tr>
<tr>
<th>All or part of filename: </th><td><asp:TextBox ID="txtfilename" runat="server" /></td>
</tr>
<tr>
<th>When was it modified?:</th>
<td>
<asp:DropDownList ID="lstDuration" runat="server">
<asp:ListItem Text="Don't remember" Value="0" />
<asp:ListItem Text="Within the last week" Value="7" />
<asp:ListItem Text="Past Month" Value="30" />
<asp:ListItem Text="Within the past year" Value="365" />
</asp:DropDownList>
</td>
</tr>
<tr>
<td colspan="2"><asp:Button ID="btnSubmit" runat="server" Text="Search" /></td>
</tr>
</table>

<asp:GridView ID="grdResults" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="None" AllowSorting="True" AllowPaging="True" PageSize="2" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Document Information">
<ItemTemplate>
<p>
<a href="http://links.10026.com/?link=<%# DataBinder.Eval(Container, "DataItem.path")%>">
<%# DataBinder.Eval(Container, "DataItem.Path")%>
</a>
<br />
<i>Last modified:
<%# DataBinder.Eval(Container, "DataItem.Write")%>
</i>
<br />
</p>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<EditRowStyle BackColor="#999999" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>

</ContentTemplate>

</atlas:UpdatePanel>
</form>
</body>
</html>

Code behind:

Partial Class Index
Inherits System.Web.UI.Page

Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click


' Bind DataGrid to the DataSet. DataGrid is the ID for the
' DataGrid control in the HTML section.
Dim source As New DataView(createDS.Tables(0))
grdResults.DataSource = source
grdResults.DataBind()

End Sub
Private Function createDS() As DataSet
Dim cnnOledb As New OleDb.OleDbConnection
Dim strQuery As String

Dim critstr As String = "(contains(filename,'.doc OR .xls OR .ppt OR .asp OR .aspx OR .txt'))"

If txtsearch.Text.Length <> 0 Then
critstr += " AND (contains(contents,'" + condition(txtsearch.Text) + "'))"
End If


strQuery = "Select DocTitle,Filename,VPath,Rank,Characterization,Write,path from SCOPE() where " + critstr + " order by write desc"

Dim connString As String = "Provider=MSIDXS;Data Source='o drive'"

Dim cn As New System.Data.OleDb.OleDbConnection(connString)
Dim cmd As New System.Data.OleDb.OleDbDataAdapter(strQuery, cn)
Dim objDS As New DataSet

cmd.Fill(objDS)

Return objDS
End Function

Function condition(ByVal srchstr As String) As String
Dim arr As String() = srchstr.Split(" ")
For i As Integer = 0 To arr.Length - 1
Dim str1 As String = arr(i)
If str1 <> "AND" And str1 <> "OR" And str1 <> "NOT" Then
arr(i) = "\" + str1 + "\"
End If
Next
Return String.Join(" AND ", arr)
End Function


Sub grdResults_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles grdResults.PageIndexChanging
grdResults.PageIndex = e.NewPageIndex
Dim source As New DataView(createDS.Tables(0))
grdResults.DataSource = source
grdResults.DataBind()

End Sub
End Class


Hi again,

I tried this out and I'm getting the same error. This turns out to be a known bug in the April CTP of Atlas. To work around it, add this code to your Page's Load event handler:

Page.ClientScript.GetPostBackEventReference(this, String.Empty);

Thanks,

Eilon


that works. Thank you. btw ATLAS ROCKS!!

Appears to be an issue in the June CTP too... and if it wasn't for this post, I'd still have the issue.

Thanks guys


Correct, this was not fixed in the June CTP. For now the one line workaround should still be sufficient.

Thanks,

Eilon


In the case of nested UserControls, does this workaround apply? If so, where should the workaround go?

I have a page which contains a UserControl, which in turn contains another UserControl, which contains a GridView wrapped in an UpdatePanel. I tried adding this line to the page's Page_Load and the UserControl's Page_Load, but I get the same generic error:

Line: 10846
Char: 17
Error: Object required
FYI, the offending line appears to be the second one pasted below:

function destroyTree(element, markupContext) {

if (element.nodeType == 1) {


Any ideas?

slp004, can you please give more details as to what you're trying to do? It sounds like other people on this thread have this scenario working so I'm curious what's going on here.

Thanks,
Eilon


I was never able to figure out exactly what the problem was, but by breaking the page up into a number of smaller pages sharing a single master page it started working again. There were just way too many UserControls inside GridView inside FormView inside UserControls inside View areas inside show/hide panels... you get the idea.

I have exactly the same problem - in the same line

 function destroyTree(element, markupContext) {if (element.nodeType == 1) {

My page have three or four levels of nested user controls inside the update panel. The curious thing is the page with the same controls has worked before some change I did - now I am trying to figure it out.


Wow, I figured out the issue.

The error was caused because I have another updatepanel in this page - inside a user control, included in master page. The user control has Visible=false. This scenario causes the error. When I set the user control visibility to true, the error goes off.

The solution is setting the updatepanel (that is inside the user control) mode to Conditional. This solves the problem even if the user control is invisible.

HTH.


I had the same problem and I set all the update panels to conditional and it worked.

Wednesday, March 21, 2012

Parser Error I got from the server

The website worked on my machine, but after I uploaded it to the server, I get the following error.

Server Error in '/' Application.

Parser Error

Description:Anerror occurred during the parsing of a resource required to servicethis request. Please review the following specific parse error detailsand modify your source file appropriately.
Parser Error Message:Could not load file or assembly 'Microsoft.Web.Atlas' or one of its dependencies. The system cannot find the file specified.
Source Error:

[No relevant source lines]


Source File: none Line: 0
Assembly Load Trace: The following information can be helpful to determine why the assembly 'Microsoft.Web.Atlas' could not be loaded.

WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].



Version Information: Microsoft .NET Framework Version:2.0.50727.42; ASP.NET Version:2.0.50727.42
--
Does anyone have some idea for this?
Thanks
I get this same error. What could it possibly be?

This is with the new December release. I double checked all my files are on the server, and correct. It is an asp.net 2.0 server.

I'm confused.
Here is the reason for these issues, although different AJAX implementations will give different errors.

I emailed godaddy.com, and sitepuppy.com (which i think is just another frontend for godaddy.), and got this reply from them:

Thank you for contactingCustomer Support. Unfortunately, we do not support the use of the AJAXhandler bundle, although we do have some limited capacity to allow theuse of java scripting. If you need to be able to use AJAX, might Irecommend the dedicated or virtual dedicated server options which wouldallow you to install whatever you like onto the operating system of theserver box. We have to keep the shared hosting servers relativelysimplified for the sake of the many different customers they each hold.We apologize for the inconvenience. Please let us know if we can helpyou in any other way.

Make sure you contact whoever it is you want to have host your sites before you try any implementation of AJAX to play around with.

I have tested, and godaddy does not work with AJAX.NET, and any others (including ATLAS).

(this is with shared hosting, btw).

It should run fine on your server, as long as you also upload Microsoft.Web.Atlas.dll. It doesn't need to be in the GAC (Global Assembly Cache) nor do you need to install anything else outside your webapplication. Just make sure you upload the Microsoft.Web.Atlas.dll inside the /bin directory in the root of your site.
I have a working version ofhttp://how2xbox.com/xbox using swirlhost's AJAX driven chatroom. It works well for the most part and it is on a go daddy hosting account.

Parser Error Message: Could not load file or assembly Microsoft.Web.Atlas or one of its de

hi all,

I have a not so nice error that I can't solve. I use asp .net 2.0 and Atlas. The site works in dev but not on my server...

I hope someone can help me out.

Regards
Stijn

Parser Error

Description:An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.

Parser Error Message:Could not load file or assembly 'Microsoft.Web.Atlas' or one of its dependencies. The system cannot find the file specified.

Source Error:

Line 1: <%@dotnet.itags.org. Page Language="C#" MasterPageFile="MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Title="Untitled Page" %>
Line 2: <%@dotnet.itags.org. Register Assembly="Microsoft.Web.Atlas" Namespace="Microsoft.Web.UI" TagPrefix="cc2" %>
Line 3: <%@dotnet.itags.org. Register Assembly="AtlasControlToolkit" Namespace="AtlasControlToolkit" TagPrefix="cc1" %>
Line 4:


Source File:/issue/default.aspx Line:2

Nobody? Do I need to give some additional info? This problem really holds up my development so please help meout here.


hello.

well, i guess that you must see if ASP.NET 2.0 is installed in IIS and if the vdir you've created there is configured to use it...


ASP .Net 2.0 is installed and the site also uses the 2.0 version. The error is about ATLAS so I think I have a configuration problem there? I use windows 2003 server.

Hello,

I have the same identically problem.

When I run my application on local web server don't have any problem, but when I transfer my aplication on remote server(Aruba) I have the problem:

Could not load file or assembly 'AtlasControlToolkit' or one of its dependencies. The system cannot find the file specified

Line 1:<%@. Page Language="C#" AutoEventWireup="true" CodeFile="Erbario.aspx.cs" Inherits="_Default" %>Line 2: Line 3:<%@. Register Assembly="AtlasControlToolkit" Namespace="AtlasControlToolkit" TagPrefix="cc1" %>Line 4:<%@. Register TagPrefix="test" Namespace="Test" %>Line 5:

Have you resolved the problem?

Help me please


MarcoLF:

I have the same identically problem.

Hi!

We are getting the same exception on our production server. Did you find out what causes it?

Thank you in advance.

Parser Error Message: The entry ScriptModule has already been added.

On my development system everything is running fine, when i publish to my beta server (SBS 2003 - *no* VS installed) I get the following error:

Parser Error Message: The entry 'ScriptModule' has already been added.

Removing this line resolves the issue but then presents me with various errors relating to not being able to load System.Web.Extensions... If i can understand why the first issue is occuring this would help! Any clues?

Hi,

I have exactly the same happening on my server, does anyone have a fix for this ?

Thanks
James

This can happen if there are two HttpModules named "ScriptModule". This can mysteriously happen if you are running a virtual directory under an asp application that already has the module defined. You can either remove the HttpModule declaration<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/> from the VD web.config, or all a remove node

<remove name="ScriptModule" />

just before adding it back.


Hi,

Excellent, thanks for the heads up.

James


That was an excellent post. Thank you for your help !

Sam


This suggest is not working for me again and again the same error only i am getting is there any other solution

please let me know soon......

Partial page rendering javascript?

This might sound silly, but I can't work out how to get the server to be able to send back some javascript to the client to run during a partial page render. I've tried scriptmanager and clientscriptmanager functions, but that doesn't seem to work. Partial page rendering doesn't seem to like response.write, and if I put the code inside a literal, I think that the AJAX framework doesn't process it. Am I missing something?

Thanks,

Martin

Hi,

could you post the code that is causing problems?


Hi,

I changed the asp.net applicaiton to ajax enable asp.net but update panal is not working. When button is clicked its doing full page refresh. When I looked at the view source script manager is not being fired.

<!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><title>
Untitled Page
</title></head>
<body>
<form name="form1" method="post" action="TestPage1.aspx" id="form1">
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTEzMjQ1MTY4NjFkZMnkklM4zF7XCrNB+Ckg0ltF70NO" />
<script src="http://pics.10026.com/?src=http://forums.asp.net/wow/Clinic/ScriptResource.axd?d=JyTA_qOIT3R2dUV6rZPpnB4caeUfuYVxGPUJUQvFvri3YW3Aua3OVlokWHAQU8raiEpmo7HCzcrEB7ckCqw8DDX6XbV0NlaftMuueWAwHqQ1&t=633068891263750000" type="text/javascript"></script>

<div id="UpdatePanel1">
<input type="submit" name="Button1" value="Button" id="Button1" />
<input name="TextBox1" type="text" value="3/9/2007 4:40:24 PM" id="TextBox1" />
</div>
<input name="TextBox2" type="text" value="3/9/2007 4:40:24 PM" id="TextBox2" />
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWBALb7diADgKM54rGBgLs0bLrBgLs0fbZDL3mTY/JT5nhMoKiVWH9R12nFdZZ" /><script type="text/javascript">
<!--
Sys.Application.initialize();
// -->
</script>
</form>
</body>
</html>

webcofig file:

<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
<sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="Everywhere"/>
<section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
<section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
</sectionGroup>
</sectionGroup>
</sectionGroup>
</configSections>
<system.web>
<pages>
<controls>
<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</controls>
</pages>
<!--

Set compilation debug="true" to insert debugging
symbols into the compiled page. Because this
affects performance, set this value to true only
during development.
-->
<compilation debug="true">
<assemblies>
<add assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add assembly="System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
<add assembly="System.Web.Extensions.Design, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Configuration.Install, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
<add assembly="Oracle.DataAccess, Version=10.2.0.100, Culture=neutral, PublicKeyToken=89B483F429C47342"/>
<add assembly="System.Data.OracleClient, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Data.OracleClient, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/></assemblies>
</compilation>
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>
</httpHandlers>
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</httpModules>
</system.web>
<system.web.extensions>
<scripting>
<webServices>
<!--Uncomment this line to customize maxJsonLength and add a custom converter -->
<!--<jsonSerialization maxJsonLength="500">
<converters>
<add name="ConvertMe" type="Acme.SubAcme.ConvertMeTypeConverter"/>
</converters>
</jsonSerialization>
-->
<!--Uncomment this line to enable the authentication service. Include requireSSL="true" if appropriate. -->
<!--<authenticationService enabled="true" requireSSL = "true|false"/>
-->
<!--Uncomment these lines to enable the profile service. To allow profile properties to be retrieved
and modified in ASP.NET AJAX applications, you need to add each property name to the readAccessProperties and
writeAccessProperties attributes.
-->
<!--
<profileService enabled="true"
readAccessProperties="propertyname1,propertyname2"
writeAccessProperties="propertyname1,propertyname2" />
-->
</webServices>
<!--
<scriptResourceHandler enableCompression="true" enableCaching="true" />
-->
</scripting>
</system.web.extensions>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
<add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</modules>
<handlers>
<remove name="WebServiceHandlerFactory-Integrated"/>
<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</handlers>
</system.webServer>
</configuration>

code behind:::

PartialClass Intake_TestPage1

Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
TextBox2.Text = Date.Now

End Sub

Protected Sub Button1_Click1(ByVal sender As Object, ByVal e As System.EventArgs)
TextBox1.Text = Date.Now
End Sub
End Class


Does anyone knows whats causing this problem....no partial page update?