OnClientClick not working - asp.net

I have a back and next button in that there is a OnClientClick validation function.
This function is not called when i click on that, Please help me
Code has given below:
<asp:Button ID="btn_view1_back" runat="server" Text="Back"
CausesValidation="False" ValidationGroup="Form2" />
<asp:Button ID="btn_View1_Next" runat="server" CausesValidation="true" Text="Next"
ValidationGroup="Form2" OnClientClick="return ValidateDropDown();"
UseSubmitBehavior ="true" />

Just to be sure: ValidateDropDown has been defined in the JavaScript, right? OnClientClick is what is executed on the client side, i.e. the javascript.
The other thing might be that the syntax for OnClientClick might need to be different, such as: OnClientClick="ValidateDropDown()"

Your question is a little unclear on which function isn't firing (the JS OnClientClick or the server-side OnClick), but if it's the server-side, make sure ValidateDropDown() is returning true. If it returns false or null or something, the server method won't fire.
Can you post your code for ValidateDropDown? Have you verified that it's firing?

The back button is set not to cause validation, and doesn't have an OnClientClick action defined.

Make sure that the validation is not firing. It can be that validation is firing and you are not able to see the Text or ErrorMessage since it is blank by default.

Your ValidateDropDown method is probably throwing an exception, which causes the postback to happen anyway.
Can you post the contents of that method?
Alternatively, use Firebug and check Break on all script errors in the debug menu.
Also, the OnClientClick code runs in the browser, and the method that it calls must be defined in Javascript, not VB.

You have a breakpoint in your validate function and it's not getting hit? Or you think it's not getting hit because your page is posting back anyway?
I would expect that ValidateDropDown function to get called, but I'm not sure. However, I also don't think it matters. I don't think it matters because it appears you are looking to prevent a postback and this isn't the way to do that. Are you looking to prevent a postback?
If so, I think the best thing to do here is to ditch the button's OnClientClick and instead add a CustomValidator control for your dropdroplist and then set the ClientValidationFunction to "ValidateDropDown". There's already an asp.net client side validation framework, so I'd just build on that.
But I'm just some idiot from the internet, I barely read your question and my reputation is 16, so I definitely wouldn't listen to me.

Related

Prevent page refresh in ASP.NET

I have the following code in my aspx file:
<button type="button" id="btnAskQuestion" runat="server" onserverclick="btnAskQuestion_Click">Ask Question</button>
I've tried every combination of onclick="return false;" and onclick="preventDefault()" I can think of, including putting them in the javascript function that gets called. Everything I try has one of two results: either I get a postback, or the server side code (btnAskQuestion_Click) never executes.
Any idea what I might be doing wrong?
You cannot execute server-side code this way, using onserverclick causes postback.
If you wish to prevent full page refresh and still execute server-side code, you have to call a client-side JS function via onclick and execute an AJAX call from there.
Another alternative is to use your button as a trigger for UpdatePanel - this way only partial postback will be performed.
Try using the property UseSubmitBehavior="false" in the button markup.
or you can use a "trick" :
Markup
<button onclick="myFunction()">Click Me!</button>
<div style="display:none">
<asp:Button runat="server" id="btnButton" .../>
</div>
js
function myFunction()
{
if (true statement)
$("[id$=btnButton]").click();
else
alert("false");
}
What this does is that you handle stuff with normal markup and do the logic using js. And you can trigger a click of the button that do something in the server.
There're OnClick, that fires on server and OnClientClick that fires on client browser. You should do this:
<asp:Button ID="btnAskQuestion" runat="server"
OnClick="btnAskQuestion_Click"
OnClientClick="return myfunction();">Ask Question</asp:button>
If myFunction returns true, then you will have a postback to the server.
My answer is appropriate only for ASP:Button, not the button control you are working with. Given the choice, I'd switch to ASP:Button.
You're looking for OnClientClick. If you put your JavaScript code there, it will kill the PostBack before it can hit the server.
On the other hand, if you're looking to execute server code without a PostBack, that's impossible. The PostBack is what triggers the server to act.

Why does CustomValidator fire on textbox's onblur

I am building a CustomValidator to handle my own application's logic on time fields ("09:00", "15:35", ...) but I am stumbling on a behaviour that I haven't found any explanation for online.
My focus right now is the validation logic that gets executed client-side.
The problem is, as said in the title, that, if and only if I set the ControlToValidate property in the Validator with the ID of the textbox I am validating, the validation gets fired as soon as focus leaves the textbox; it even fires before the onblur event, which is absolutely detrimental for me, since I am using the onblur event to standardize the time formats (eg "9:00" -> "09:00", "11.45" -> "11:45") and thus, the validation logic potentially receives an incorrect value. If, on the other hand, the ControlToValidate property remains blank, the ClientValidationFunction is fired only on a submit/postback.
The only related answer I've found is this https://stackoverflow.com/a/8649697/450684, but still, to me it makes no sense at all. Why should the presence of a ControlToValidate indicate that I want client-side validation to execute before onblur? I don't want it! Is there any way to supress this behaviour?
Here is an example page:
<asp:TextBox runat="server" AutoPostBack="false" ID="txtBox1" onblur="FormatText(this);" />
<asp:CustomValidator runat="server" ID="CV1" ControlToValidate="txtBox1" ClientValidationFunction="Test1" />
<asp:CustomValidator runat="server" ID="CV2" ClientValidationFunction="Test2" />
<asp:Button ID="btn1" Text="postback" runat="server" OnClick="btn1_Click" />
<asp:Label ID="lbl1" runat="server" />
<script type="text/javascript">
function FormatText(txtBox1)
{
alert('FormatText');
}
function Test1(val, args)
{
alert('Test1');
}
function Test2(val, args)
{
alert('Test2');
}</script>
What I want is both Test1 and Test2 to execute only on btn1's click; instead on txtBox1's onblur event I get Test1 and FormatText executing in this order
ASP.NET's client validation was really fun for me to write and study, don't let this ruin everything :-)
Thx
PS: .NET framework's version is 4.0. Plus, the server-side language is C#, if it matters
I think what is going on is this:
The standard behavior for ASP.NET client-side validation is to validate when the field is exited. That's an observation, not a reference to a published standard (although there may be one.) The out-of-the-box validators all behave this way. All of them require specifying a particular field to validate.
The custom validator allows you to validate a single control (by specifying it with ControlToValidate), or lets you validate a combination of controls, in which case you set ControlToValidate to an empty string. Unless things have changed, you do have to specify it; if you omit the attribute, no validation will occur.
So ... if you specify a control to validate, the custom validator behaves like every other validator and reacts to the user exiting the field. If you don't specify a control to validate, it doesn't know what controls you're interested in, and doesn't do that.
You may be able to work around this by writing a truly custom validator: inherit from BaseValidator. That can actually be a lot of fun.
How to manage events of validation for your control.
You can remove ControlToValidate property from your validator and bind validation for your textbox on textbox event as you wish. You can add some function logic before or after validation also. On button click event validation stay the same without change.
function BindValidation(){$('#txtBox1').on('blur keyup change',function(){ValidatorValidate($('#CV1').get(0));});}
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(BindValidation);
//validation function example for CV1 validator
function Test1(val, args)
{
args.IsValid=$('#txtBox1').val().length>0&&$('#txtBox1').val().match(/^\s+$/g)==null;
}

LinkButton not firing ASP.NET validators

I have a form that currently uses an control to submit a form. Everything works perfectly. So now the new requirement is for the "submit' button to be a link. Changing it to a LinkButton control, without changing a SINGLE other thing, breaks the validation.
There is a bit too much code to post in a SO question and I know there's a bit of a lack of detail here, but is there any reason why a LinkButton wouldn't fire ASP.NET validation the same way a Button control would? In theory, they should both operate exactly the same, no?
The current submit button:
<asp:Button ID="btnSubmit" TabIndex="9" Text="Send" ValidationGroup="Forward" runat="server" />
The new submit button:
<asp:LinkButton ID="btnSubmit" TabIndex="9" Text="Send" ValidationGroup="Forward" runat="server" />
The Link button should fires the validation the same way a normal button does, my concerns in your case would be the following:
make sure these is nothing in the server side code stopping this.
make sure in the javascript code there is nothing stopping the "
ASP.NET controls that fire validation has a property called CauseValidation
Be sure all controls should fire validation, has this property set to True
Add attribute CauseValidation="True" to your control but if you want to fire this at particular line at code behind you can use validate the form by the following code:
FormID.Validate();
I know this is old but it has never answered. Did your validator have a "controlTovalidate"? Currently it would appear as if the validator was not firing but in reality it is. It just does not have anything that it is 'watching'. Hope if anyone reaches this thread that this helps even if it is just a little bit.
I was unable to determine the cause of this issue but was able to solve it:
I set the CausesValidation="false" and added at the top of the onclick event this.Validate(linkButton.ValidationGroup) this allows the event to get to the code behind and validation to occur.

Button not processing onClick method

I have a button on an ascx control that calls a method on the onClick event:
<asp:Button id="bUpdateText" onClick="FUpdate" ValidationGroup="Update" CausesValidation="False" Text="Update" cssclass="button" runat="server" />
Normally I use this control on it's own page and the button works. This time round however, I am loading this control into a Div that is present on the home page of my site (that way I can show the contents with a little bit of JQuery). However, when I bring the control in this way, the onClick event doesn't fire and I am not sure what could cause that.
Sorry I don't have any code sample but the nature of the site makes it difficult to provide any that would make sense.
In short, what would stop this event firing now?
p.s I have tried adding validation groups to all other buttons and validation controls on the page and there is only ONE form present on the page.
EDIT: I have only just added the validation stuff in to see if that does anything. By default it has been like this and still didn't work:
<asp:Button id="bUpdateText" onClick="FUpdate" Text="Update" cssclass="button" runat="server" />
As mentioned as well, this works when I use this control on it's own page (loaded directly into Default.aspx) so I don't think the case of onClick matters.
EDIT2: I have just noticed that when I click this button, other validation controls on my page are being triggered even though they have their own DIFFERENT validation group?! Taking these controls out doesn't help though.
Thanks.
I have found out what is causing the issue.
This control that I am now including is called on the Page_Finalize() and I am guessing that by this point the viewstate has forgotten it needs to do anything. Loading this control on the page load sorts it out.
Thanks for looking.
To start, if you set the 'causesValidation' property to false, you do not need a validation group.
Additionally, I believe that ASP cares about case when dealing with the OnClick command.
i.e. it should be OnClick not onClick
Yeah, annoying and small, but that might be your problem
You can use Firebug to see what happen in Update validationGroup. it looks like your page execute only client-side button click because of Update validationGroup.

How to prevent PostBack on the client side?

I have some validation JS code on client, that must be executed befor PostBack.
If this validation code return 'false', postback is needless.
How it can be disabled?
Remember that the real validation should always happen on the server. Anything you do client-side is merely an optimization to save a few http round trips.
The easiest way to keep your client side and server-side validation in sync with ASP.Net is to use the validation controls. The validation controls will do both client side and server side validation, in such a way that if validation fails on the client it never posts to the server.
If you want to do something that's not covered by the standard validation controls, you should either use a CustomValidator or inherit your own control from BaseValidator.
Set the OnClientClick='YourJSValidationFunction' on your ASP button.
Then have the YourJSValidationFunction return true or false.
False will prevent postback
Example:
http://vijaymodi.wordpress.com/2007/06/08/button-onclick-and-onclientclick-2/
If the postback is being triggered by a button then you can do something like this:
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="return IsValid();" />
If the IsValid function returns false then the postback will be prevented.
If you want to catch all postbacks regardless of which control triggers it then you can use <form id="form1" runat="server" onsubmit="return IsValid();">
What do you use: some validator or some button with onclick event?
If you have
<input type="button" id="btnID" runat="server" onclick="CheckValid();"/>
function CheckValid()
{
if(!IsValid) return false;//then no post back occer
}
Depending on the validation you're attempting, you may also be able to use the CustomValidator control. This would also allow you to easily implement your validation logic on the server side.

Resources