Event isn't firing when using javascript to postback - asp.net

I'm trying to use Telerik's RadSpell to spellcheck some text when the user submits it.
The way this is supposed to work is by stopping the postback, triggering the spellcheck through javascript, then in the spellcheckfinished event manually starting the real postback. The problem is that in the last step the Clicked event isn't firing for the button and the server side event handler never gets called.
Here is the relevant .aspx code:
<script type="text/javascript" language="javascript">
var spellCheckFinished = false;
var btnClicked;
function doSpellCheckStuff(btnTrigger)
{
btnClicked = btnTrigger;
var spell = GetRadSpell('<%= rsMessage.ClientID %>');
// spell.add_clientCheckFinished(checkFinished);
spell.startSpellCheck();
return false;
}
function checkFinished(sender, args)
{
args.SuppressCompleteMessage = true;
setTimeout('MySubmit();', 100);
}
function MySubmit()
{
WebForm_DoPostBackWithOptions(
new WebForm_PostBackOptions(btnClicked.id, '', true, '', '', false, true)
);
}
</script>
<tr>
<td>
<asp:Button ID="btnSubmit" OnClientClick="return doSpellCheckStuff(this);" Text="Submit"
OnClick="btnSubmit_Click" runat="server" />
</td>
<telerik:RadSpell ID="rsMessage" ControlToCheck="txtMessage" ButtonType="None"
UseClassicDialogs="true" FragmentIgnoreOptions="All"
OnClientCheckFinished="checkFinished" runat="server" />
</tr>
Any idea why btnSubmit_Click isn't getting called and how I can fix it?

Try to inject your postback script as :
string script = #"function MySubmit(){" +
this.Page.ClientScript.GetPostBackEventReference(myButton, string.Empty);
"}";
if (!this.Page.ClientScript.IsClientScriptBlockRegistered("myPostBackScript"))
{
this.Page.ClientScript.RegisterClientScriptBlock(typeof(MyPage), "myPostBackScript", script, true);
}

The last like of doSpellCheckStuff() is returning false always, which stops the OnClick event listener from running.

Related

Prevent double clicking asp.net button

I realise this question has been asked but none of the answers worked for my project.
I have a button that when clicked calls an API, so there is a 1 second delay.
I have tried several things nothing works.
btnSave.Attributes.Add("onclick", " this.disabled = true; " + ClientScript.GetPostBackEventReference(btnSave, null) + ";");
Even that does nothing.
Prevent Double Click .Please add below code in your aspx page.
<script type="text/javascript" language="javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
function BeginRequestHandler(sender, args) { var oControl = args.get_postBackElement(); oControl.disabled = true; }
</script>
This solution is simple and effective. On your button include this code:
OnClientClick="return CheckDouble();"
And wherever you want your JavaScript - e.g. At the bottom of your page:
<script type="text/javascript">
var submit = 0;
function CheckDouble() {
if (++submit > 1) {
alert('This sometimes takes a few seconds - please be patient.');
return false;
}
}
</script>
Most of the above suggestions failed to work for me. The one that did work was the following by tezzo:
Me.btnSave.Attributes.Add("onclick", "this.disabled=true;")
Me.btnSave.UseSubmitBehavior = False
Simpler still, rather than using the above in the code-behind, just use the following:
<asp:Button ID="btnSave" runat="server" Text="Save"
UseSubmitBehavior="false"
OnClientClick="this.disabled='true';"
</asp:button>
UseSubmitBehavior="false" is the key.
You can prevent double-clicking using this code:
Me.btnSave.Attributes.Add("onclick", "this.disabled=true;")
Me.btnSave.UseSubmitBehavior = False
So you can use btnSave_Click to call your API.
Usually I have a lot of Validators in my Page: setting Validator.SetFocusOnError = True I can run this code to reenable save button if a validation failed.
Me.YourControl.Attributes.Add("onfocus", Me.btnSave.ClientID & ".removeAttribute('disabled');")
This is the one I found works in all cases.
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button1" OnClick="Button1_Clicked" />
<asp:Button ID="Button2" runat="server" Text="Button2" />
</form>
Now here’s the short JavaScript snippet that will disable the button as soon as it is clicked so that when PostBack occurs the button cannot be clicked again.
<script type = "text/javascript">
function DisableButton() {
document.getElementById("<%=Button1.ClientID %>").disabled = true;
}
window.onbeforeunload = DisableButton;
</script>
The above script disables the ASP.Net Button as soon as the page is ready to do a PostBack or the ASP.Net form is submitted.
But in cases you might want to disable all Buttons and Submit Buttons on the page hence for such cases I have created another function which disables all Buttons and Submit buttons whenever there’s a PostBack or form submission
<script type = "text/javascript">
function DisableButtons() {
var inputs = document.getElementsByTagName("INPUT");
for (var i in inputs) {
if (inputs[i].type == "button" || inputs[i].type == "submit") {
inputs[i].disabled = true;
}
}
}
window.onbeforeunload = DisableButtons;
</script>
Prevent Double Click .Please add below code in your aspx page
<script type = "text/javascript">
function DisableButton() {
document.getElementById("<%=Button1.ClientID %>").disabled = true;
}
window.onbeforeunload = DisableButton;
</script>
At first my solution is like this:
<script>
function disableButton(btn) {
setTimeout(function () { btn.disabled = true; }, 20);
return true;
}
</script>
<asp:Button runat="server" ID="btnSave" Text="Save" OnClick="btnSave_Click" OnClientClick="return disableButton(this);" />
Without setTimeout the button will be immediately disabled and then the OnClick event will not be fired. The drawback of this approach is that the Save button will not be accessible anymore if some validation fails or some error happens.
So I don't think disable the button is a good solution, and come up with another solution:
function disableButton(btn) {
if (btn.hasclicked) return false;
btn.hasclicked = 1;
btn.onmouseenter = function () { this.hasclicked = 0; };
return true;
}
But my colleague points out that if the post processing is very slow, before it is finished, the user is still able to perform the double postback by leave-enter-click the button. So I figured out another two solutions:
Run the validation from client before submitting the form. But if your page contains multiple ValidationGroup, it is said that the following Page_ClientValidate() should be called multiple times with a passed-in ValidationGroup parameter: e.g. Page_ClientValidate("group1"):
function disableButton(btn) {
if (Page_ClientValidate) {
Page_ClientValidate();
if (!Page_IsValid) {
btn.setAttribute("btnClicked", "n");
return true;
}
}
if (btn.getAttribute("btnClicked") == "y") {
return false;
} else {
btn.setAttribute("btnClicked", "y");
return true;
}
}
As the ASP.NET has only one form in a page (not ASP.NET MVC), we can also let the onsubmit client event of the form to intercept the double click:
function disableButton(btn) {
$("form").submit(function () {
if (btn.getAttribute("btnClicked") == "y")
return false;
else
btn.setAttribute("btnClicked", "y");
return true;
});}
I'll ask QA to test those two approaches(Post edit: QA has proved that it is very dangerous to use this approach. Please refer to my following comments for details).
Try this way, it's a working solution:
For all browsers including Opera Mobile browser which doesn't support js, means your form will not be blocked in that type of browsers.
Add this in Page_load() method:
BtnID.Attributes.Add("onclick", "if(typeof (Page_ClientValidate) === 'function' && !Page_ClientValidate()){return false;} this.disabled = true;this.value = 'Working...';" + ClientScript.GetPostBackEventReference(BtnID, null) + ";");

javascript error handling

I have a javascript function for checking errors which I am calling on OnClicentClick event of a button. Once it catch a error I want to stop execution of the click event. But in my case it always it always executes the onclick event.
Following is my function:
function DisplayError() {
if (document.getElementById('<%=txtPassword.ClientID %>').value.length < 6 || document.getElementById('<%=txtPassword.ClientID %>').value.length > 12) {
document.getElementById('<%=lblError.ClientID %>').innerText = "Password length must be between 6 to 12 characters";
return false;
}
var str = <%=PhoneNumber()%>;
if(str.length <10)
{
alert('<%=phoneNum%>'.length);
document.getElementById('<%=lblError.ClientID %>').innerText = "Phone Number not in correct format";
return false;
}
}
button html code:
<asp:Button runat="server" Text="Submit" ID="btnSubmit" ValidationGroup="submit" onclick="btnSubmit_Click" OnClientClick="DisplayError()"/>
It should not execute the button click event once it satisfies any of the IF condition in the javascript function.
Use OnClientClick="if (!DisplayError()) return false;"
That way, if no error occurred, it will still postback, but only when an error occurs, it will return false, and cancel the postback.
Use OnClientClick="return DisplayError();"

Display confirmation box in ASP.NET using JavaScript

I need to show the confirm box "Are you sure You Want To continue?" If "Yes" I need the ASP.NET textbox value to be cleared out. Otherwise it should not be cleared.
function doConfirm(){
if (confirm("Are you sure you want to continue?")){
var mytxtbox = document.getElementById('<% =myAspTextBox.ClientID %>');
mytxtbox.value = '';
}
}
Note the myAspTextBox refers to the name of the asp:textbox controls ID property
<asp:textbox ID="myAspTextBox" runat="server" OnClientClick="javascript:doConfirm();"
Hope this helps
In your asp textbox tag add this:
OnClientClick="javascript:testDeleteValue();"
...
And add this script:
<script>
function testDeleteValue()
{
if (window.confirm('Are you sure You Want To continue?'))
document.getElementById("<%=<th id of your textbox>.ClientID%>").value = '';
}
</script>
If you want this to happen on click of your radio box, put it in this tag and just replace onclientclick with onclick.
<input type='radio' onclick='testDeleteValue()'/>
If you download the AjaxControlToolkit you can use the ConfirmButtonExtender to display a simple confirmation box to a user after a button is clicked to proceed with the action or cancel
You can see here for an example and here for a tutorial on how to implement this
Okay I just noticed the bit about radio buttons, in any case the AjaxControlToolkit is a good place to start if you want to implement JavaScript solutions in .Net projects
if this is your textbox markup:
<asp:textbox id="txtInput" runat="server" />
and then this is the button that will trigger the confirm:
<asp:button id="btnSumbit" runat="server" onclientclick="return clearOnConfirm();" text="Submit" />
then you'll need the following javascript:
<script type="text/javascript">
function clearOnConfirm() {
if (confirm("Are you sure you want to continue?")) {
document.getElementById("<%=txtInput.ClientID %>").value = '';
return true;
} else {
return false;
}
}
</script>
If all you want to do is to clear the textbox but always continue with the postback then you don't ever need to return false as above but always return true as below. In this scenario you should rethink the message you display to the user.
<script type="text/javascript">
function clearOnConfirm() {
if (confirm("Are you sure you want to continue?")) {
document.getElementById("<%=txtInput.ClientID %>").value = '';
}
return true;
}
</script>
function stopTimer() {
if (window.confirm('Are you sure You Want To continue?')) {
$find('Timer1')._stopTimer()
return true;
}
else {
return false;
}
<asp:Button ID="Btn_Finish" runat="server" Text="Finish" Width="113px" OnClick="Btn_Finish_Click" OnClientClick="return stopTimer();" Height="35px"
protected void Btn_Finish_Click(object sender, EventArgs e)
{
Timer1.Enabled = false;
// if any functions to be done eg: function1();
Response.Redirect("~/Default2.aspx");
}
There is also a timer stop doing in the function. The confirmation box if press "Ok" timer stops and also its redirected to new page "Default2.aspx"
else if chosen cancel then nothing happens.

Telerik RadWindow Javascript return values to ASP.NET

I have a parent page that launches a telerik radwindow and passes it an argument.
Once the radwindow is done processeing the value, I need it to return it to the parent page, and I would like the parent page to have access to this value in my code behind page.
I have tried to pass the value to a hidden field on my page and then trigger a page refresh and my code behind watches to see if the value is working.
I can't seem to get this to work. I get the return value in the parent javascript, but i can't get it from my hidden field from the code behind.
I even get it into the text box like i need to but, when i find the Hidden field in the codebehind, there is no value set.
Where I have set alerts, I am getting the values displayed as i need to.
I suspect that the reason I can't see my return value in the code behind file, is that when the page is refreshed, I am getting a new page and not only causing a post back.
And is there not a better way i can do this.
here is my code in the parent page:
Parent ASPX:
<script type="text/javascript">
function OpenWnd() {
var oWnd = radopen(null, "RadWindow1");
}
function OnClientShow(oWnd) {
//Create a new Object to be used as an argument to the radWindow
var arg = new Object();
//Using an Object as a argument is convenient as it allows setting many properties.
arg.text = document.getElementById("TextBox1").value;
//Set the argument object to the radWindow
oWnd.Argument = arg;
}
function ClientCallBackFunction(radWindow, returnValue) {
//check if a value is returned from the dialog
if (returnValue.newtext) {
document.getElementById("Hidden1").value = returnValue.newtext;
alert("HiddenValue: " + document.getElementById("Hidden1").value);
}
}
</script>
<form id="form1" runat="server">
<telerik:RadScriptManager ID="RadScriptManager1" runat="server">
</telerik:RadScriptManager>
<div>
<telerik:RadWindowManager ID="RadWindowManager2" runat="server">
<Windows>
<telerik:RadWindow ID="RadWindow1" runat="server" OnClientShow="OnClientShow" ClientCallBackFunction="ClientCallBackFunction"
NavigateUrl="Dialog2.aspx" />
</Windows>
</telerik:RadWindowManager>
</div>
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True"></asp:TextBox>
<input type="button" value="Send content to dialog page" onclick="OpenWnd()" />
<p>
<input id="Hidden1" type="hidden" runat="server" />
</p>
</form>
Parent Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
HtmlInputHidden hidden = (HtmlInputHidden)Page.FindControl("Hidden1");
if (IsPostBack && !string.IsNullOrEmpty(hidden.Value))
{
//Code Here
}
}
Here is my Dialog code:
Dialog ASPX:
<script type="text/javascript">
function GetRadWindow() {
var oWindow = null;
if (window.radWindow) oWindow = window.radWindow;
else if (window.frameElement.radWindow) oWindow = window.frameElement.radWindow;
return oWindow;
}
function ConfigureDialog() {
//Get a reference to the radWindow wrapper
var oWindow = GetRadWindow();
//Obtain the argument
var oArg = oWindow.Argument;
//Use the argument
var oArea = document.getElementById("TextBox1");
oArea.value = oArg.text;
}
function SendAndClose() {
var oWindow = GetRadWindow();
//Get current content of text area
var arg = new Object();
arg.newtext = document.getElementById("TextBox1").value;
oWindow.Close(arg);
RefreshParentPage();
}
function RefreshParentPage() {
GetRadWindow().BrowserWindow.location.reload();
alert("RefreshParentPage");
}
</script>
Thanks for all the help
Ian
You are doing the following
GetRadWindow().BrowserWindow.location.reload();
But that wont cause a postback it will simply reload the parent page, you need to cause a potback.
You could try adding a button to the parent form with the style set 'display:none', and handling the click event in the code behind, you can fire this button off from your js code.
In Parent Page :
<asp:Button runat="server" id="btnClick" Style="display:none" OnClick="btnClick_Click"/>
protected void btnClick_Click(object sender,EventArgs e)
{
string val = this.Hidden1.Value; //Code goes here
}
You can invoke from your javascript like this (non jQuery), place this in your callback
document.getElementById('<%= btnClick.ClientID').click();
A better approach would be this on the aspx side:
<%=this.ClientScript.GetPostBackEventReference(new System.Web.UI.PostBackOptions(btnClick))%>

Page_ClientValidate is validating multiple times.

problem i have is that, the validation summary message(alert) is displayed twice. I cannot figure out the reason.
Please help.
Here is the code
function validate() //javascript function
{
if (typeof(Page_ClientValidate) == 'function')
{
var isPageValid = Page_ClientValidate();
if(isPageValid)
{
}
}
}
<asp:Button ID="btn1" runat="server" OnClientClick="validate()" Text="button"
ValidationGroup="ContactGroup" />
<asp:ValidationSummary ID="ValidationSummary1" runat="server" DisplayMode="List"
ShowMessageBox="true" ShowSummary="false" ValidationGroup="ContactGroup" />
The problem is that the function Page_ClientValidate takes an input parameter, if you don't specify the input then the validationsummary triggers once per groupname.
In your case, the function triggers twice: once for groupname="ContactGroup" and another time for groupname=""
you should change
var isPageValid = Page_ClientValidate();
to
var isPageValid = Page_ClientValidate('');
if you don't want to specify a ValidationGroup, or if you want to specify a groupname then you need to call Page_ClientValidate like so:
var isPageValid = Page_ClientValidate('ContactGroup');
First of all you should lose the ValidationGroup="ContactGroup" from the button because having validation group in it will first call of the validation on the page then the OnClientClick event that contains the validate function which will call the page validation once again.
Then you should pass the validation group "ContactGroup" to the Page_ClientValidate() function so it knows which controls to validate because simply calling Page_ClientValidate() will validate all controls regardless of their validation group(and it may display the validation message more than once, depending on how many validation groups you have).
In short do something like this:
function validate() //javascript function
{
if (typeof(Page_ClientValidate) == 'function')
{
var isPageValid = Page_ClientValidate('ContactGroup');
if(isPageValid)
{
//your custom code
}
}
}
<asp:textbox id="txtMyBox" runat="server"/>
<asp:requiredFieldValidator Id="rfv1" runat="server" ControlToValidate="txtMyBox"
ValidationGroup="ContactGroup" ErrorMessage="Bad!"/>
<asp:Button ID="btn1" runat="server" OnClientClick="validate()" Text="button"/>
<asp:ValidationSummary ID="ValidationSummary1" runat="server" DisplayMode="List"
ShowMessageBox="true" ShowSummary="false" ValidationGroup="ContactGroup" />
just return false from the function and change the OnClientClick as shown below:
<asp:Button ID="btn1" runat="server" OnClientClick="return validate();" Text="button"
ValidationGroup="ContactGroup" />
function validate() //javascript function
{
if (typeof(Page_ClientValidate) == 'function')
{
var isPageValid = Page_ClientValidate();
if(isPageValid)
{
}
}
return false;
}
There is no need to manually call the Page_ClientValidate function, unless you're wanting to do the validation outside of a postback attempt.
Set the buttons CausesValidation to true. That'll run the validation.
You can make validation without show messages, use the following code segment,then use isPageValid variable:
if (Page_ValidationSummaries && Page_ValidationSummaries[0] && Page_ValidationSummaries[0].showmessagebox) {
var showMessagesOption = Page_ValidationSummaries[0].showmessagebox;
Page_ValidationSummaries[0].showmessagebox = "False";
isPageValid = Page_ClientValidate();
Page_ValidationSummaries[0].showmessagebox = showMessagesOption;
}
I know this is an old post, but here's a solution that may be more flexible. Similar to other users suggestions, this solution accepts the validation group that is passed by default by the asp.net validation controls. This way you would not need to add the OnClientClick="validate()" on the Button control.
//Make sure the Page_ClientValidate function exists
if (typeof (Page_ClientValidate) == "function") {
//Stash the old implementation in a temp variable
Page_ClientValidateOld = Page_ClientValidate;
//Create a new implementation and store it
//in Page_ClientValidate. Callers will now get
//this implementation.
Page_ClientValidate = function (validationGroup) {
var isValid;
//Call the old implementation first…
isValid = Page_ClientValidateOld(validationGroup);
//and then call our extension
if (!isValid) {
// Do something
}
return isValid;
}
}
If you want to read more on this approach, I recommend that you look at this blog post:
http://hyperthink.net/blog/interception-patterns-in-javascript/
Remove the click event of the button, that forces second validation I think.
remove the onclientclick event of button there is no need for that

Resources