I have a very long form that has to be filled out. I have maintainScrollPositionOnPostBack enabled as I have multiple controls that hide/show based on user input.
Since the form is long I'd like for the page to focus and scroll to the first control that caused validation to fail and I have the focus on validation fail option enabled. However, it seems that maintainScrollPositionOnPostBack overrides this (the control does focus but doesn't scroll up to it).
Any ideas for workarounds for this? Everything I've tried so far hasn't worked. It is an asp.net webforms project.
This is a good question and really tricky to get working. But I managed to get one version that you can try and maybe build on.
The MaintainScrollPositionOnPostback="true" -setting sets a series of javascript-events on form submit and window load and these do as you say, "overwrite" the focus set by the validator.
So what I did was add a common css-class to all validators like so:
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" CssClass="error" ErrorMessage="RequiredFieldValidator" SetFocusOnError="true"
EnableClientScript="false" ControlToValidate="TextBox1"></asp:RequiredFieldValidator>
And then I added another eventlistener to window.load (note we need to leave also the one that Asp.Net has added so we cannot do windows.load = function...):
<script>
window.addEventListener("load", function () {
var el = document.getElementsByClassName("error");
if (el.length > 0) {
window.location.hash = "#" + el[0].id;
}
});
</script>
Here you might benefit from jQuery use to be able to support more browsers but addEventListener is pretty well supported.
The script searches for the errormessage and focus on that by it's id with anchor. Javascript has focus-method but it's for form elements so that's why this workaround.
Hope this helps!
I have a page with a repeater containing RadioButtonLists which have requiredFieldValidators attached to them. I need to keep the RFV next to the control (it's the only way I can get it to work to be honest!)
However, the form is made up of a few sections contained in an accordion. This means that when the form is submitted, the item that has failed validation may not be visible, so the user won't know where the error is.
Is there a way I can also have a message by the submit button which is triggered by an RFV changing saying "please go back and check your answers" or something? I guess I'd need to use JQuery / JavaScript as it would be clientside.
There is a special ValidationSummary control for that:
<asp:ValidationSummary ID="Summary" runat="server"
DisplayMode="SingleParagraph"
HeaderText="Please go back and check your answers" />
This control is used to summarize all validation errors on the page.
Try "ValidationSummary". look for example from here.
http://www.w3schools.com/aspnet/control_validationsummary.asp
Ive got ASP:Button on my page:
OnClientClick="return CheckTerms();" CssClass="submit" OnClick="BtnRegister_OnClick" />
OnClientClick I do js to check something and according to the check result I would like to proceed postback or not.
On all browsers it works (when false is returned from OnClientClick there is no postback) but situation is different on ie 7 where postback goes
any hints ?
thank You very much for help
for the sake of clarity here is the code that doesnt work either:
function CheckTerms() {
return false;
}
Here is how buttons are rendered:
IE
chrome:
<input type="submit" name="ctl00$plhMain$Register$btnRegister" value="??????????????????" onclick="return CheckTerms();" id="ctl00_plhMain_Register_btnRegister" class="submit">
Please notice that I use PIE.htc on my inputs but on button no.
what is this ? jQuery16100078065287469022415
My guess is that an error is being thrown in IE7, and when an error is thrown it doesn't return false, and it will continue on with the postback. You probably used a method that's not supported in IE7, or that acts differently than intended. Without the actual javascript method and any relevant markup I couldn't say for sure though.
iv'e got an asp button which performs another task besides postback
i have done this by adding javascript code to the button as follows
if( !IsPostBack )
btn1.Attributes.Add("onclick", "f();");
i'm not sure of 2 things
the first :
where in the cs code i should add the function f() , currently i'm doing it in page load
while ignoring postbacks because then the function would have already been added(i might be wrong)
the second :
is there any to make the function execute only if the page was validated ? (after postback)
thanks in advance
eran.
I would use OnClientClick instead of adding the click event throug the attributes. As for your JavaScript, I would add it in the ASPX part. Depending on what the function does, you might be able to avoid the code behind all together and do something like this:
<asp:Button ID="Button1" runat="server" Text="Hi" OnClientClick="javascript:return f();" OnClick="Button1_Click" />
From your f() function, kick off the validation, and return true if validation passes, otherwise return false. If OnClientClick returns true the page will post back, and if it returns false the page will not post back.
1st Question
You will need to add it each time.
btn1.Attributes.Add("onclick", "f();");
2nd Question
You can check the validity of a page by checking the Page.IsValid Property
Unobtrusive JavaScript
If you're serious about javascript then you don't want to write inline javascript.
You will want to create an event handler in javascript code inside the script tags or in a external file.
If you're using .NET 4 server control id:s will be good, else I would use jquery's
contains selector. Search for the given server control ID.
The __doPostBack is not working in firefox 3 (have not checked 2). Everything is working great in IE 6&7 and it even works in Chrome??
It's a simple asp:LinkButton with an OnClick event
<asp:LinkButton ID="DeleteAllPicturesLinkButton" Enabled="False" OnClientClick="javascript:return confirm('Are you sure you want to delete all pictures? \n This action cannot be undone.');" OnClick="DeletePictureLinkButton_Click" CommandName="DeleteAll" CssClass="button" runat="server">
The javascript confirm is firing so I know the javascript is working, it's specirically the __doPostBack event. There is a lot more going on on the page, just didn't know if it's work it to post the entire page.
I enable the control on the page load event.
Any ideas?
I hope this is the correct way to do this, but I found the answer. I figured I'd put it up here rather then in a stackoverflow "answer"
Seems it had something to do with nesting ajax toolkit UpdatePanel. When I removed the top level panel it was fixed.
Hope this helps if anyone else has the same problem. I still don't know what specifically was causing the problem, but that was the solution for me.
Check your User Agent string. This same thing happened to me one time and I realized it was because I was testing out some pages as "googlebot". The JavaScript that is generated depends on knowing what the user agent is.
From http://support.mozilla.com/tiki-view_forum_thread.php?locale=tr&comments_parentId=160492&forumId=1:
To reset your user agent string type about:config into the location bar and press enter. This brings up a list of preferences. Enter general.useragent into the filter box, this should show a few preferences (probably 4 of them). If any have the status user set, right-click on the preference and choose Reset
I had this same problem (__doPostBack not working) in Firefox- caused a solid hour of wasted time. The problem turned out to be the HTML. If you use HTML like this:
<input type="button" id="yourButton" onclick="doSomethingThenPostBack();" value="Post" />
Where "doSomethingThenPostBack" is just a JavaScript method that calls __doPostBack, the form will not post in Firefox. It will PostBack in IE and Chrome. To solve the problem, make sure your HTML is:
<input type="submit" id="yourButton" ...
The key is the type attribute. It must be "submit" in Firefox for __doPostBack to work. Other browsers don't seem to care. Hope this helps anyone else who hits this problem.
this might seem elemental, but did you verify that your firefox settings aren't set to interfere with the postback? Sometimes I encounter similar problems due to a odd browser configuration I had from a debugging session.
Is it because you are doing return confirm? seems like the return statement should prevent the rest of the code from firing. i would think an if statement would work
if (!confirm(...)) { return false; } _doPostBack(...);
Can you post all the js code in the OnClick of the link?
EDIT: aha, forgot that link button emits code like this
<a href="javascript:__doPostBack()" onclick="return confirm()" />
Are you handling the PageLoad event? If so, try the following
if (!isPostBack)
{
//do something
}
else if (Request.Form["__EVENTTARGET"].ToLower().IndexOf("myevent") >= 0)
{
//call appropriate function.
}
Check if you are getting a call this way, if so then maybe the event is not wired and nedes to be explicitly called.
what do you expect from "Enabled = 'false'" ?
I have had problems with firebug on some web forms, something to do with the network analyser can screw with postbacks.
With or without the OnClientClick event it still doesn't work.
The _doPostBack event is the auto generated javascript that .NET produces.
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
*The &95; are underscores, seems to be a problem with the stackoverflow code block format.
Now that i think about it, as noted in my last edit, you want to drop the javascript: in the on client click property. It's not needed, because the onclick event is javascript as it is. try that, see if that works.
Seems it had something to do with nesting ajax toolkit UpdatePanel. When I removed the top level panel it was fixed.
Hope this helps if anyone else has the same problem.
I had this exact same issue in a web app I was working on, and I tried solving it for hours.
Eventually, I did a NEW webform, dropped a linkbutton in it, and it worked perfectly!
I then noticed the following issue:
...
I switch the order to the following, and it immediately was fixed:
...
IE had no issue either way (that I noticed anyway).
I had a similar issue. It turned out that Akamai was modifying the user-agent string because an setting was being applied that was not needed.
This meant that some .NET controls did not render __doPostBack code properly. This issue has been blogged here.
#Terrapin: you got this exactly right (for me, anyways).
I was running User Agent Switcher and had inadvertently left the Googlebot 2.1 agent selected.
In Reporting Services 2008 it was causing the iframes that reports are actually rendered in to be about 300x200 px, and in Reporting Services 2008 R2 is was throwing "__doPostBack undefined" errors in the Error Console.
Switching back to the Default User Agent fixed all my issues.
I had the same problem with Firefox. Instead of using __doPostBack() could you use the jQuery .trigger() method to trigger a click action on an element that has your postback event registered as the click action?
For example, if you had this element in your aspx page:
<asp:Button runat="server" ID="btnMyPostback" OnClick="btnMyPostback_Click" CssClass="hide" ToolTip="Click here to submit this transaction." />
And your postback event in your controller:
protected void btnMyPostback_Click(object sender, EventArgs e)
{
//do my postback stuff
}
You could do the postback by calling:
$("#btnMyPostback").trigger("click");
This will cause the Page_Load event to fire if you need to do something on Page_Load.