imagebutton with onclientclick isn't firing onclick event - asp.net

I have an imagebutton with an postbackurl and an onclientclick script. When i added the onclientclick code, if my javascript validation passes (aka returns true), the page just seems to perform a postback (the screen just seems to refresh itself), rather than post to the postbackurl. Any ideas why this is happening?
Sample:
<asp:ImageButton ID="imgSendInfo" runat="server" SkinID="SendInfo" PostBackUrl="MyUrlOnAnotherSite" onClientClick="javascript:return onFormSubmit(this.form);return document.MM_returnValue" />
UPDATE:
OK, so I decided to change what JS functions I'm calling now since calling Multiple functions definitely wasn't helping. Here's my updated code. All I'm doing now is validating a single textbox and returning true or false. Even this simple function is causing the postback URL to never get called. Could it have anything to do with the fact that I'm trying to call a function to return a true or false?
My validation function:
function valForm() {
if (document.getElementById('FName').value == '') {
alert('no');
return false;
}
else {
alert('yes');
return true;
}
}
My ImageButton:
<asp:ImageButton ID="imgSendInfo" runat="server" SkinID="SendInfo" PostBackUrl="SetOnCodeBehind" onClientClick="javascript:return valForm();" />

OK figured out a workaround. I REMOVED the return statement from the onclientclick, since the return is what was messing with the postback. I then added requiredfieldvalidators to the page, but Im not displaying any text. This way, 2 sets of validation are occurring (booo), but the first displays my alert messages (this is how the client wants validation performed), and the second prevents the form from posting.
My imagebutton:
<asp:ImageButton ID="imgSendInfo" runat="server" SkinID="SendInfo" PostBackUrl="SetOnCodeBehind" ValidationGroup="enroll" CausesValidation="true" onClientClick="javascript:onFormSubmit(this.form);document.MM_returnValue;" />
My requiredfieldvalidation group:
<asp:RequiredFieldValidator ID="reqVal1" runat="server" ErrorMessage="" ValidationGroup="enroll" ControlToValidate="FName" InitialValue="" />
<asp:RequiredFieldValidator ID="reqVal2" runat="server" ErrorMessage="" ValidationGroup="enroll" ControlToValidate="LName" InitialValue="" />

Did you know that your onClientClick js-function returns twice? return document.MM_returnValue never gets reached.
Is your PostBackUrl's page in your application? You can even validate the previous page on serverside:
If Page.PreviousPage.IsValid Then
' Handle the post back
Else
Response.Write("Invalid")
End If
For further information: MSDN LinkButton.PostBackUrl

Related

ASP.NET checkbox won't postback when onclick is defined

I intend to answer my own question here - I think this could be difficult to fathom. I have two checkboxes, the second of which has a postback, which should only fire if the first one is checked. Here's what I wrote
<asp:CheckBox ID="chkTC" runat="server" Text="I have read and accept the Terms & Conditions" /><br />
<asp:CheckBox ID="chkRegister" runat="server" AutoPostBack="true" onclick =" var bOK = document.getElementById('chkTC').checked; if (!bOK) { alert('You must agree to the Terms and Conditions'); } return bOK; " />
The onclick code is a copy the code I use if I want to determine if a button should postback.
However, there was no postback from the second checkbox, even if the first was ticked.
I found that ASP.NET doesn't have a defined 'onclick' property for checkboxes, but will pass any onclick code supplied through to the generated HTML. However, it also utilises the onclick attribute to effect the postback. The onclick code that I supplied was prepended to the code that makes the postback happen. And because I used a return statement, it was not being executed. Sorry if this is obvious - it wasn't to me.
So the fix is to only execute a return when I don't want the postback
<asp:CheckBox ID="chkRegister" runat="server" AutoPostBack="true" onclick =" var bOK = document.getElementById('chkTC').checked; if (!bOK) { alert('You must agree to the Terms and Conditions'); return false; }" />

How to use a custom ValidatorUpdateDisplay function when the controls / validators are loaded on postback in an UpdatePanel the first time?

In ASP.NET when using validation controls (i.e. RequiredFieldValidator) the client sided framework will execute the JS function Page_ClientValidate. This function will validate all controls on the page (of the given ValidationGroup) and call the JS function ValidatorUpdateDisplay with a parameter of the DOM element of the span tag of the validator control.
ValidatorUpdateDisplay toggles the visibility of the span tag depending on the result of the validation.
In my web application I've overridden the ValidatorUpdateDisplay JS function to provide more functionality on the validation scenario (i.e. red borders around the controls, showing popover on the first failed control and scrolling to it).
Now this works very well until my controls (incl. submit button) are shown the first time after a postback in an UpdatePanel.
<asp:ScriptManager runat="server" />
<asp:UpdatePanel ID="upTest" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button ID="bShow" runat="server" UseSubmitBehavior="false" Text="SHOW" OnClick="bShow_Click" />
<asp:Panel ID="pContent" runat="server" Visible="false">
<asp:TextBox ID="tbTest" runat="server" />
<asp:RequiredFieldValidator ID="rfvTest" runat="server" ControlToValidate="tbTest" Text="Not valid" />
<asp:Button ID="bTest" runat="server" UseSubmitBehavior="false" Text="TEST" />
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
<script type="text/javascript">
function ValidatorUpdateDisplay(val) {
debugger; // this will not be reached
}
</script>
protected void bShow_Click(object sender, EventArgs e)
{
this.pContent.Visible = true;
}
After initial load press bShow to display pContent.
Now, if you leave tbTest.Text empty and press on bTest it should enter the overridden ValidatorUpdateDisplay function, however it enters the function of the framework and displays "Not valid" from rfvTest.
If you change pContent.Visible to true and press bTest after initial load the desired effect will happen: It will enter the custom ValidatorUpdateDisplay function and not display "Not valid".
If you move the button bTest out of the UpdatePanel the problem persists.
How can I make it work inside an UpdatePanel?
ASP.NET uses a lazy loading approach to insert the ValidatorUpdateDisplay function when it needs it the first time, hence in my example it will load the function after the postback of the UpdatePanel.
This will override my own implementation of the ValidatorUpdateDisplay function, because it's inserting the function at the end of the page.
There is a dirty workaround, I just inserted an empty CustomValidator on initial load that is always valid:
<asp:CustomValidator runat="server" />
I wish there was a cleaner solution.

Can I create an ASP.NET ImageButton that doesn't postback?

I'm trying to use the ImageButton control for client-side script execution only. I can specify the client-side script to execute using the OnClientClick property, but how do I stop it from trying to post every time the user clicks it? There is no reason to post when this button is clicked. I've set CausesValidation to False, but this doesn't stop it from posting.
I know this problem has already been answered but a simple solution is to return false from the HTML onclick method (i.e. the ASPX OnClientClick method) e.g.
<asp:ImageButton ID="ImageNewLink" runat="server"
ImageUrl="~/images/Link.gif" OnClientClick="DoYourStuff(); return false;" />
Returning false stops the browser from making the request back to the server i.s. stops the .NET postback.
Here's one way you could do it without conflicting with the postback functioning of other controls:
Define your button something like this:
<asp:Button runat="server" Text="Button" UseSubmitBehavior="false" OnClientClick="alert('my client script here');my" />
The "my" ending in the handler for OnClientClick is a way to alias asp.net's __doPostBack client event that forces the postback; we simply override the behavior by doing nothing similar to this script:
<script type="text/javascript">
function my__doPostBack(eventTarget, eventArgument) {
//Just swallow the click without postback of the form
}
</script>
Edit: Yeesh, I feel like I need to take a shower after some of the dirty tricks that I need to pull in order to get asp.net to do what I want.
Another solution would be to define a PostBackUrl that does nothing
<asp:imagebutton runat="server" PostBackUrl="javascript:void(0);" .../>
<image src="..." onclick="DoYourThing();" />
Use a server side Image control
<asp:Image runat="server" .../>
Pretty sure you can add the client onclick event to that.
Solution 1
<asp:ImageButton ID="btn" runat="server" ImageUrl="~/images/yourimage.jpg"
OnClientClick="return false;" />
OR
Solution 2
<asp:ImageButton ID="btn" runat="server" ImageUrl="~/images/yourimage.jpg"
OnClientClick="yourmethod(); return false;" />
In addition (solution 2), your javascript method may be in this form
<script type="text/javascript">
function yourmethod() {
__doPostBack (__EVENTTARGET,__EVENTARGUMENT); //for example __doPostBack ('idValue',3);
}
</script>
in code behind
protected void Page_Load(object sender, System.EventArgs e)
{
if (this.IsPostBack) {
string eventTarget = this.Request("__EVENTTARGET") == null ? string.Empty : this.Request("__EVENTTARGET");
string eventArgument = this.Request("__EVENTARGUMENT") == null ? string.Empty : this.Request("__EVENTARGUMENT");
}
}
This works Great for me:
Use OnClientClick to write your script and PostBackUrl="javascript:void(0);" to avoid postback.
<div class="close_but">
<asp:ImageButton ID="imgbtnEChartZoomClose" runat="server" ImageUrl="images/close.png" OnClientClick="javascript:zoomclosepopup();" PostBackUrl="javascript:void(0);" />
</div>
Use OnClientClick to write your script and PostBackUrl="javascript:void(0);" to avoid postback

Stop postback on TextChanged

I have a textbox in an aspx page that has a TextChanged event attached to it.
I also have a validator attached to the textbox.
When the text is changed, the validate triggers but in case there is an error the textchanged event is still called. Do you know if it's possible to stop the postback on textchanged if the validator fires?
<asp:TextBox ID="txtQuantity" runat="server" AutoPostBack="true" ontextchanged="txtQuantity_TextChanged"></asp:TextBox>
<asp:RequiredFieldValidator ID="reqQuantity" ControlToValidate="txtQuantity" runat="server" ErrorMessage="The quantity is mandatory."></asp:RequiredFieldValidator>
You can move validation to client side adding EnableClientScript="true" attribute. Postback won't occur as check will be performed with JS.
Other than that you can check whether page is valid when performing callback function for TextChanged event so that to define whether function can proceed. You should add ValidationGroup attribute to your validator and call Page.Validate function specifying that group before Page.IsValid is checked.
Upd
Here's the tip.
Add your own JS function, e.g.:
function IsValid( args ) {
if( args.value.length == 0 ) {
return false;
}
else {
return true;
}
}
In Page_Load event add this code:
txtQuantity.Attributes[ "onchange" ] = "if ( IsValid(this) == false ) return;";
This won't mess up auto postback when input is correct, but will prevent postback otherwise.
Add CausesValidation="true" for the text box and it will be good. If the validation is not valid there won't be any post-back.
<asp:TextBox ID="txtQuantity" runat="server" AutoPostBack="true" ontextchanged="txtQuantity_TextChanged" CausesValidation="true"></asp:TextBox>
Just sharing an inline, shorter version of the accepted answer:
<asp:TextBox ID="txtQuantity" runat="server"
AutoPostBack="true" ontextchanged="txtQuantity_TextChanged"
onchange="if (this.value.length == 0) return;"></asp:TextBox>
Having the same problem with a RequiredFieldValidator, the above worked for me.
Known nag: the designer complains that "onchange" is not a valid server-side attribute.
try it after change AutoPostBack="true" as AutoPostBack="false"..
What I do is in my client validation function I test the event type I am in. If the event shows me in a change event, I claim the validation passed and leave.
if (event.type === 'change') {
args.IsValid.true;
return;
}
I believe this is the best solution as you can leave the validator wired up and the textbox set as you like and no longer worry about the change event causing the validation.

DropdownList autoposback after client confirmation

I have a dropdownlist with the autopostback set to true. I want the
user to confirm if they really want to change the value,
which on post back fires a server side event (selectedindexchanged).
I have tried adding an onchange attribute "return confirm('Please click OK to change. Otherwise click CANCEL?';") but it will not postback regardless of the confirm
result and the value in the list does not revert back if cancel
selected.
When I remove the onchange attribute from the DropdownList tag, the page does postback. It does not when the onchange attribute is added. Do I still need to wire the event handler (I'm on C# .Net 2.0 ).
Any leads will be helpful.
Thanks!
Have you tried to set the onChange event to a javascript function and then inside the function display the javascript alert and utilize the __doPostback function if it passes?
i.e.
drpControl.Attributes("onChange") = "DisplayConfirmation();"
function DisplayConfirmation() {
if (confirm('Are you sure you want to do this?')) {
__doPostback('drpControl','');
}
}
You can utilize the the CustomValidator control to "validate" dropdown by calling a javascript function in which you do the confirm():
<asp:DropDownList ID="TestDropDown" runat="server" AutoPostBack="true" CausesValidation="true"
ValidationGroup="Group1"
OnSelectedIndexChanged="TestDropDown_SelectedIndexChanged">
<asp:ListItem Value="1" Text="One" />
<asp:ListItem Value="2" Text="Two" />
</asp:DropDownList>
<script type="text/javascript">
function ConfirmDropDownValueChange(source, arguments) {
arguments.IsValid = confirm("Are you sure?");
}
</script>
<asp:CustomValidator ID="ConfirmDropDownValidator" runat="server"
ClientValidationFunction="ConfirmDropDownValueChange" Display="Dynamic" ValidationGroup="Group1" />
The following works when the DropDownList is triggering partial postbacks:
// caching selected value at the time the control is clicked
MyDropDownList.Attributes.Add(
"onclick",
"this.currentvalue = this.value;");
// if the user chooses not to continue then restoring cached value and aborting by returning false
MyDropDownList.Attributes.Add(
"onchange",
"if (!confirm('Do you want to continue?')) {this.value = this.currentvalue; return false};");
Currently, you're always returning the result of the confirm(), so even if it returns true, you'll still stop execution of the event before the postback can fire. Your onchange should return false; only when the confirm() does, too, like this:
if (!confirm('Please click OK to change. Otherwise click CANCEL?')) return false;
Overriding the onchange attribute will not work if you have have AutoPostBack set to true because ASP.NET will always append the following to the end of your onchange script:
;setTimeout('__doPostBack(\'YourDropDown\',\'\')', 0)
If you set AutoPostBack to false, then overriding onchange with a "confirm and __doPostBack" type script (see above, err.. below) will work but you may have to manually create the __doPostBack function.
if (!confirm('Please click OK to change. Otherwise click CANCEL?')) return false;
Always returns so dropdownlist's OnSelectedIndexChanged event fires whether user clicks OK or CANCEL.
Make sure your event is wired:
dropDown.SelectedIndexChanged += new EventHandler(dropDown_SelectedIndexChanged);
You can also apply a client-side attribute to return the confirmation. Set the index accordingly if cancelled.
dropDown.Attributes.Add("onchange", "javascript: return confirm('confirmation msg')");
<asp:DropDownList runat="server" ID="ddlShailendra" AutoPostBack="True" OnSelectedIndexChanged="ddlShailendra_SelectedIndexChanged" onchange="javascript: { if(confirm('Click ok to prevent post back, Cancel to make a postback'))return true;} " >
<asp:ListItem Text="tes" Value="1" ></asp:ListItem>
<asp:ListItem Text="test" Value="-1"></asp:ListItem>
</asp:DropDownList>
Write the function inline and dont have a "return" for the condition in which you want a post back. This works and is as per the standards.

Resources