ASP.NET 3.5 validation groups not working - asp.net

I wish I could paste in my markup, but it's too complex and contains a lot of references to the client's company name. I am hoping someone with vast experience might be able to point me in the right direction.
We have a master page with a ValidationSummary that is not part of a validation group. On our content page, we have another ValidationSummary that is assigned to a validation group called ValReject. On the content page is also a CustomValidator that uses ClientValidationFunction and a button, both of which are also assigned to ValReject.
When I click the button, the client function executes once, but the error reports to both validation summaries, the one on the content page and the on on the master page. I even added a third validation summary and set its group to something like "asdf", but it gets reported to, as well, meaning all three validation summaries are showing the same error on the page.
I then created a separate ASP.NET test project, pasted all the code in, and ran it and it validates like it should.
I then played around with AutoEventWireup on the content page. When I set it to false, validation works, but the page load event doesn't fire. What's up with that?
I know you probably need code samples, but, like I said, I just can't do that without going through a huge headache (trust me, the master and content page markup is huge.
The question here is: Does anyone have an idea of what could cause a single validator to report to ALL validation summaries on the page even though only one of them shares the same validation group as the validator and button?
edit: When I pasted the markup into my test app, I did have to remove some tags to get it to work since the test app doesn't have references to some assemblies used by the real master page. Some things I removed are:
<%# Register Assembly="RadMenu.Net2" Namespace="Telerik.WebControls" TagPrefix="radM" %>
<radM:RadMenu ID="RadMenu1" runat="server" DataSourceID="smdsMenu" Skin="CssGrey" ClickToOpen="True" EnableViewState="False" CausesValidation="false" />
So the fact that it works on my test app leads me to the conclusion that we're doing something on our production app that I am not doing in my test app. Yes, I know this is vague, but perhaps a light bulb will go off in someone's head.

Man, after hours and hours of spinning my wheels, I finally figured it out. We use this extension method to disable double clicks of buttons:
public static void DisableDoubleClick(this Button Control)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("if (typeof(Page_ClientValidate) == 'function') { ");
sb.Append("if (Page_ClientValidate() == false) { return false; }} ");
sb.Append("this.disabled = true;");
sb.Append(Control.Page.ClientScript.GetPostBackEventReference(Control, ""));
sb.Append(";");
Control.Attributes.Add("onclick", sb.ToString());
}
This is what was messing up the validation as it was invoking global validation. I fixed this by making the following change:
sb.Append(string.Format("if (Page_ClientValidate({0}) == false) {{ return false; }}}} ",
Control.ValidationGroup == string.Empty ? string.Empty : string.Format("\"{0}\"", Control.ValidationGroup)));
What clued me in was when I set AutoEventWireup to false to see what would happen. This kept the page load event from firing which is where the above extension method was being called. What a needle in the haystack, this problem.
I don't blame anyone for not answering due to lack of details, but I will keep this up in case anyone else can use it.
edit: Thanks to slfan and gbs. I had just figured out the issue and was coming back here to post my answer when I see that you two were essentially tackling my issue from both sides of the problem. The page load event is where the binding was occurring and the extension method being called was messing up the Page_ClientValidate function. Since you both are technically right and I can't award both of you the answer, I hope no one gets upset if I mark my own as the answer here. You two are definitely good at analyzing such issues with minimal details and no code samples. Props.

The AutoEventWireup causes ASP.NET to call the Page_Load event automatically without having to register to an event. An alternative could be to override the OnLoad method. Your page seems to work properly when Page_Load is not called. What do you do inside this method? Some strange data bindings? What if you uncomment this code, will it work then? Like this you could narrow your problem down to the real problem which you are not showing in your question.

Two things I would look for:
1: Any external validation using Page_ClientValidate being done in javascript
2: Any explicit call to Page.Validate() in code-behind

Related

SP2010 - httpcontext.response.write() not working for LinkButton's onClick event

probably a simple oversight I've missed (though I vaguely recall some obscure blogpost about the inner workings of Response.Write not working as expected in some situations but I don't remember if this is one of them):
The situation is, I have a Link Button on a control running in SP2010, and if I don't use HttpContext.Response.Write(), everything works as expected (ie I can change the .Text value for a Label). However, if I call Context.Response.Write(), while I can debug and step through the code, nothing seems to happen any more (nothing is written back and changes to other controls do not appear). It's being run on an application page in _layouts, appearing in a modal dialog.
(basically, I'm trying to do this - http://acveer.wordpress.com/2011/01/25/using-the-sharepoint-2010-modal-dialog/ but it doesn't work. EDIT: If I change it to a asp:Button, it still doesn't work)
Here's some code if you're interested:
.aspx:
# Page Language="C#" AutoEventWireup="true" ...
<asp:LinkButton CssClass="button remove" runat="server" OnClick="remove_Click" Text="Remove" ID="remove"></asp:LinkButton>
.aspx.cs:
public void remove_Click(object sender, EventArgs e)
{
....
//if successful
HttpContext context = HttpContext.Current;
if (HttpContext.Current.Request.QueryString["IsDlg"] != null)
{
testControl.Text = "test code";
//doesn't work, and prevents line above from working
Context.Response.Write("<script type='text/javascript'>alert('hi!');</script>");
Context.Response.Flush();
Context.Response.End();
// context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup()</script>");
// context.Response.Flush();
// context.Response.End();
}
}
Anyone come across something similar?
EDIT: some more interesting pieces that may help,
The button itself lies within an UpdatePanel
I do have a AsyncPostbackTrigger assigned
Using Response.Write from Web Forms code behind is problematic at best. As a rule of the thumb: never ever use Response.Write from a Web Forms page or user control.
The reason Response.Write is problematic, is because it is not part of the page's control tree, and rendering infrastructure. This means that when used within events in it will output the text outside of the normal page flow, and usually outside of the proper HTML page structure.
This is also why things go awry when you're using them in combination with UpdatePanels. As UpdatePanels are specifically designed to replace parts from a page, the infrastructure needs to know which parts. A Response.Write happens completely outside of this, and there's no real way of knowing where to render it. At best, the ScriptManager will perform a Response.Clear to wipe out your Response.Writes, at worst you'll break the UpdatePanel protocol body and you'll get a JavaScript error.
To top things off, any literal <script> tag will be ignored when you're performing a partial page update, as the browser's innerHTML feature used to fill in the HTML fragments sent by the server does not execute <script> tags.
Now, with all this theory out of the way -- is there no way to execute a piece of JavaScript code through an UpdatePanel? It turns out there is, and it's a lot cleaner than just executing a Response.Write: ScriptManager.RegisterClientScriptBlock and ScriptManager.RegisterStartupScript. For example:
ScriptManager.RegisterClientScriptBlock(
theButton, // control or UpdatePanel that will be rendered
typeof(YourPage), "UniqueKey", // makes your script uniquely identifiable
"alert('Testing!');", true);
The important part is the first argument: now the ScriptManager will know when to execute your script. If you register it on a control that is not updated on a partial page refresh, your script will not execute. But if the UpdatePanel containing the control is refreshed, your script that is hooked up to it will also execute. And that's usually exactly what you want.
If you always want to execute your script, regardless of which panel updates, you'd call
ScriptManager.RegisterClientScriptBlock(Page, ... );
#Ruben provided a very good answer, but I felt I could add useful content that doesn't fit in a comment.
There are a few occasions in SharePoint where you use a Response.Write - namely when dealing with webparts that are displayed within a SharePoint Modal popup and you want to do something cute with the callback when using window.frameElement.commitPopup().
The fact that you are using Response.Write within an update panel is actually part of your issue. When a postback that was generated with an update panel returns, the response is formatted with UpdatePanelId|Response Content where UpdatePanelId is the div associated with the update panel and Response Content is the new inner HTML of the div. When you use response.write, that format is lost, therefore the ScriptManager has no idea what to do with the response and should ignore it as erroneous. #Ruben provided you a method of registering scripts within an UpdatePanel.
Context.Response... should have a lower case context
ie:
context.Response.Flush()
etc
or am I missing the point?

Failed to load viewstate. The control tree into which viewstate is being loaded

I am receiving the following error message after an HTTP POST on an ASP.NET form hosted inside a UserControl:
Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request. For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request.
Here's additional info:
I'm running .NET 4.5 RC
It's an Umbraco 4.7-based website
On my local dev machine the form works perfectly
This error only occurs on the staging server which has .NET 4.5 (only), MSSQL 2012 Express, IIS 7.5, Windows 7 (I know, it's not a real server yet, one day maybe...)
The server is not part of a web farm (or garden, tho that should be irrevelant)
The user control does render controls dynamically
I have applied all the latest service packs.
I have run out of ideas now! I have even restarted it and also performed a richual over the server involving a song and a special dance to no avail.
What is important when you are adding controls dynamically is on which event you are adding them.
If you added controls on events that occur after load, they will be part of the viewstate you send to the client.
You will have to add those controls again before LoadViewState is called.
If you run into cases where the decision of which controls to add is itself stored in the ViewState or the value of a control, then remember even before the ViewState is loaded, this data is available in Request.Params
Refer the asp.net page life cycle
I just added EnableViewState="false" to my page placeholder and its gone. Hope it works for u as well.
This Error Mainly Occurs during View state Change: From One Template To other Template like in case of Item Template, Edit Item Template, in Controls like Form View, List Views, Detail View, Grid View in ASP .net (all frameworks);
While Changing from control states say Item Template ---> Edit Template
the followings were going to alter
1) Controls will change (its ID & states)
2) Its Positions will change.
While Transformation of view if any post back occurs you will get Error as
Failed to load viewstate. The control tree into which viewstate is
being loaded....
if you are using separate control for data-binding like (button,link_button_Image_button events) you will get this error reported !
To avoid this error >>> Once state changes from one template to other within method you call data source binding ( Don't call during click or any post backing events ).
OK, so the answer is literally: "Set up a new server with all the same software as the last one and try again" and it works now.
I add "name" attribute with the same value as id, then this problem is gone.
<input type="button" id="extractBomInfoBtn" name="extractBomInfoBtn" value="Extract" class="button textonly" />
I had the same issue. This issue was at client end but it didn't occur in my local system.
After hours of googling, i had written EnableViewState="false" to my table tag in aspx page which has all the dynamic controls and then i removed all the viewstate variables and instead i created some hidden textboxes in the aspx page and accepted DB values into them in code behind and used them throughout my code. It then solved my problem.
But still, i couldn't figure out what was exactly the problem.
In my case I was manipulating the .Text property of a asp:Literal on page load which was causing the issue. In all other cases this never caused me a viewstate error but in this particular case I was changing the .Text value to an html element.
The following caused the error:
<asp:Literal ID="SvgIcon" runat="server" />
SvgIcon.Text = "<svg version=\"1.1\" id=\"Layer_1\" bla bla />"
I was able to resolve the error by adding EnableViewState="false" explicitly to the control:
<asp:Literal ID="SvgIcon" runat="server" EnableViewState="false" />
Check if you have the binding method of the control directly in your page load event. This can cause this problem.
You can add new PlaceHolder per UserControls
OR
You can set enableviewstate=false on the control , if you dont need viewstate
In my case I had a grid view with (OnPageIndexChanging) event
and when I click on a page nothing will happen until I click it twice!
I was refreshing the data source before setting new page index.
This is what I was doing wrong
grd.DataSource = data;
grd.DataBind();
grd.PageIndex = e.NewPageIndex;
This is the right way
grd.PageIndex = e.NewPageIndex;
grd.DataSource = data;
grd.DataBind();
This can happen if you override SaveViewState in your control but don't override LoadViewState.
So I actually ended up discovering that the list of entities I was binding to was not in the same order as the controls in ViewState! I'm still working thru a cleaner solution, but my code is working with ViewStateEnabled = true by having the method which reconstructs my dynamic controls (called from Page_Load) do it differently if !IsPostBack.
Ultimately, I will probably need to fix my sorting algorithm for my nested dynamic controls, but suffice it to say: if you are using the same pattern as I am, of using a List to generate/bind to dynamic controls, and that order is fluid or changing, try comparing Request.Params to find the keys that are relevant to your control hierarchy, and see if they match the order of your List. That solved my issue. Kudos to #nunespascal!
In short, I am dynamically generating all but one tab in an AjaxToolkit tab control, and then populating that with a couple layers deep of placeholders and regular controls (textboxes, dropdownlists, etc), so that's why it's complicated to get the order of everything correct.
Although this is very old question, I had visited this as I got the similar issue. But my issue was generated just because I have added a javascript code in Master page in head tag. That javascript code is reading a value of Session["KeyName"] ,
Code is like below -
$(document).ready(function () {
var allowOpenInNewTab = false;
allowOpenInNewTab = '<%# Convert.ToString(Session["AllowOpenInNewTab"]).ToLower() %>' == 'true';
if (!allowOpenInNewTab && window.sessionStorage.tabId != '1') {
alert("This page is not allowed to be open in another tab, sorry we can not load the page!!");
}
});
When I remove above code then everything was running smoothly but if I keep adding this part of code, it was giving this error of
Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate...
Finally I found the solution like if I move my javascript code from head to just before the end of the body tag.
So solution that worked for me was moving javascript code (which is reading Session value from Server tags) to just before end of body tag.

Problem with asp.net C# focus, page_load

I'm really new to asp.net and have a couple of issues I'm trying to get fixed. I have some programming experience, but it is not asp.net. However, I've been able to follow the code enough to make other changes in the code to fix other issues.
The first is this:
I'm working with a form that has a calculate amount method that gets called when the user inputs a value in an amount text box. The same method gets called when the next control, number of payments, has a value.
So in the two controls:
onTextChanged="ctrlName_textChanged"
Then in the code behind, the textchanged method does:
calculateAmount();
The problem is after the amount is calculated and returns, the focus seems to get reset and the user has to tab all the way back through the form to the place they were.
The textboxes in question are in a panel that starts out hidden and is made visible conditionally.
My apologies if I have not used the proper .net terminology.
It looks like the same issue may be causing my second problem. When the user types in an amount and then tabs and quickly adds the number of payments, you can see the amount get calculated correctly and very shortly displays the proper total in the total amount text box. However, even though it shows for that short time, the tab order again gets reset as well as the total amount value.
I've looked at different methods to try and fix the focus issue.
In the textchanged method, I tried using something like:
Session["myval"] = "someval";
Then tried to check against that in Page_Load with something like:
if(Session["myval"] != null) {
this.NextControl_Name.Focus();
}
but it didn't ever work correctly.
I also tried to set a cookie in that same textchanged method using something like this:
Response.Cookies["myval"].Value = "somevalue";
Then tried to check that in Page_Load using something like the previous if block above but using Request.Cookies["myval"] as the source.
Is there a good reference with some really clear code samples I can look at for this type of implementation?
Thank you in advance,
C.
Sounds like you have a postback problem...
Remember that the web is stateless. This means that when you have a web page rendered out in .NET and you attach an event that executes serverside code... it does an HTTP POST back to the server which is effectively a new page request. The Page_Load method will fire again as well as your bound event. So your onTextChanged event is firing a new request back to the server. This is why you see the focus reset and why when you tab quickly, the value seems to disappear magically.
You can do one of several things, you can implement the UpdatePanel in the AjaxControlToolkit
http://www.asp.net/ajax/ajaxcontroltoolkit/samples/
you can use PageMethods and do your validation with javascript and jQuery (or other js library)
see page method info http://www.geekzilla.co.uk/View30F417D1-8E5B-4C03-99EB-379F167F26B6.htm
Hope this helps

ASP.Net UpdatePanel ImageButton causes "this._postbackSettings.async is null or not an object"

I get this error on an update panel within a popupControlExtender which is within a dragPanelExtender.
I see that a lot of other people have this issue and have various fixes none of which have worked for me.
I would love to hear a logical explanation for why this is occurring and a foolproof way to avoid such issues in the future.
I have found that like others maintain this error does not occur when the trigger is a LinkButton rather than an ImageButton, still wondering if anyone has an explanation.
I've had the same problem and haven't really found any satisfying solution until I ended up on https://siderite.dev/blog/thispostbacksettingsasync-is-null-or.html which does exactly what I want.
Just to avoid problems with possible dead links in the future here is the code:
var script = #"
if (Sys &&
Sys.WebForms && Sys.WebForms.PageRequestManager &&
Sys.WebForms.PageRequestManager.getInstance)
{
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (prm &&
!prm._postBackSettings)
{
prm._postBackSettings = prm._createPostBackSettings(false, null, null);
}";
ScriptManager.RegisterOnSubmitStatement(
Page,
Page.GetType(),
"FixPopupFormSubmit",
script);
In case of a submit without the _postBackSettings being set it creates them, causing the null reference exception to disappear as _postBackSettings.async is then available.
Hope this helps,
G.
My best guess is that the UpdatePanel is not able to write out the custom "async" property to the postback request properly. This is likely due to blocking from one of the controls wrapping it (my gut feeling is that it's the popupControlExtender - it tends to have odd behavior with updatepanels, as it is intended to manage the events inside it for it's show/hide purposes).
I would recommend either removing the updatepanel and rolling your own solution for your specific business need for having it there, or implementing your own popup script (probably slightly easier to write).
Incidentally, for some background, the "this._postbackSettings.async" is your AJAX.NET framework trying to figure out whether this is an async call or not. You might be able to overcome it by setting this programaticly before the postback is sent (catch the postback event and add the field to the postback request if it is not already there).
Just some thoughts...I do not believe there is a "plug and play" answer for this one!
Settign "EnablePartialRendering" to false on the ScriptManager control prevents the error, but it is not an optimal solution. Losing the benefit of partial rendering could be a big deal, depending on your application.
Just for the record, I wasn't doing exactly the same as other folks who saw the error. I have a PopupControlExtender, in which is a checkboxlist. I added a "select all" link with a javascript method to programmatically select/deselect all. I'm not using an Imagebutton. I didn't see the error before adding the javascript and now even after removing it the error remains. There has to be another change I'm missing.
I hope this helps someone...
--Matt

Double postback issue

I have a ASP.NET 1.1 application, and I'm trying to find out why when I change a ComboBox which value is used to fill another one (parent-child relation), two postbacks are produced.
I have checked and checked the code, and I can't find the cause.
Here are both call stacks which end in a page_load
First postback (generated by teh ComboBox's autopostback)
Postback call stack (broken)
Second postback (this is what I want to find why it's happening)
alt text (broken)
Any suggestion? What can I check?
It's a very specific problem with this code, I doubt it will be useful for someone else, but here it goes:
A check was added to the combo's onchange with an if, if the condition was met, an explicit call to the postback function was made.
If the combo was set to AutoPostback, asp.net added the postback call again, producing the two postbacks...
The generated html was like this:
[select onchange="javascript: if (CustomFunction()){__doPostBack('name','')}; __doPostBack('name','')"]
First thing I would look for is that you don't have the second ComboBox's AutoPostBack property set to true. If you change the value in the second combo with that property set true, I believe it will generate a postback on that control.
Do you have any code you could share? Double post backs plagued me so much in classic ASP back in the day that it was what finally prompted me to switch to .NET once and for all. Whenever I have problems like these for .NET, I go to every CONTROL and every PAGE element like load, init, prerender, click, SelectedIndexChanged, and the like and put a breakpoint.
Even if I don't have code there, I'll insert something like:
Dim i As Integer
i = 0
I am usually able to pinpoint some action that I wasn't expecting and fix as needed. I would suggest you do that here.
Good luck.
Check Request.Form["__EVENTTARGET"] to find the control initiating the postback - that may help you narrow it down.
Looking at the callstacks, and some Reflectoring (into ASP.NET 2 - I don't have 1.1 handy) - it looks like SessionStateModule.PollLockedSessionCallback is part of the HttpApplication startup routines. It may be possible that your app is being recycled - I'm pretty sure an event gets written into the Event log for that.
My only other suggestion would be Fiddler or something on the client to capture HTTP traffic.
This is very old post, but people still looking at this for solution exactly same as I did last week.
Like Grengby said Double events are primary reasons - but removing one of them is not allways an option. Atleast on my case and I had to resolve this on 3rd party's application.
I added following script and amended ASP form on masterpage:
<script>var Q = 0;</script>
<form id="Form1" runat="server" onsubmit="Q++; if(Q==1){return true;} else { return false;}">
This seems to be working and please forward your comments.
Arun
http://www.velocityreviews.com/forums/t117900-asp-net-multiple-postback-issue.html

Resources