Avoid postback on button click - asp.net

I have a Search feature. if the search string is empty and user clicks "GO" then the postback of the gridview shouldn't happen and the alert (as mentioned in below code) should get fired up.
My gridview is in update panel. Below is the logic that i have written but it doesn't works.
protected void btnGo_Click(object sender, EventArgs e)
{
if (!txtSearchString.Text.Equals(string.Empty))
{
BinGrid();
upnl1.update //update panel is updated here.
}
else
{
ScriptManager.RegisterStartupScript(this.upnl1, this.GetType(), "Search", "alert('Enter search text');", false);
//upnlgvOpportinities.Update();
//upnlAdmin.Update();
return;
}
}
Please help! Let me know if any info is needed

This logic is wrong. It should do using javascript if you want to avoid the postback at first place.
Have your javascript return false when textbox is empty and true when not
<asp:button runat="server".... OnClientClick="return myfunction(); " />
You can check if textbox is empty or not in myfunction()

Replace Your ScriptManager line with below code line.
ScriptManager.RegisterStartupScript(this.upnl1, this.GetType(), "Script", "alert('Enter search text');", true);

If you don't want a request to the server to be sent (if I understood your needs right), than you need a client-side solution, that is handle button click with javascript and conditionally prevent the postback. However your current code is server-side, and is executed on a server after the postback has occurred.
As to client-side, here is one possible way. Define a js function that simply checks the value of the search box and returns false if it is empty. On the button click simply call this function. If a click handler returns false, further processing of the button click will be stopped and the postback won't occur:
function checkSearch() {
var searchBox = document.getElementById('HereComesSearchBoxClientID');
if (searchBox.value == '') {
alert('Enter search text');
return false;
} else {
return true;
}
}
<asp:Button ID="SearchButton" runat="server" Text="GO" OnClick="ServerSideHandler" OnClientClick="checkSearch();" />

#Madhur Ahuja's way is the correct one. Expanding that a little bit more.
HTML
<asp:Button ID="txtSearchString" runat="server"
OnClientClick="javascript:return CheckifEmpty(this);" />
Javascript
function CheckifEmpty(objSearchBox) {
//always trim, otherwise it will accept a string of spaces
var isEmpty = objSearchBox.value.trim() == "";
if (isEmpty) {
alert('Enter search text');
}
return !isEmpty;
}
if (!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^\s*(\S*(?:\s+\S+)*)\s*$/, "$1");
};
}

Related

how to check if validationgroup passed?

Currently working with UserControls.
Have this button :
<dx:ASPxButton ID="btnSave" runat="server" Text="Save" CssClass="btn btn-active" ValidationGroup="MyValidationGroup" OnClick="BtnSaveClick">
I inherited this code from my team mates.
Recently i discovered that if button is clicked multiple times, it duplicates the record.
I tried to add
btnSave.ClientEnabled = false;
and
btnSave.Enabled = false;
into the code behind, but it's not preventing from duplicating the records.
How to check if validation group passed (successfully) into jquery or javascript, than disable the button on the front end ?
Any idea ?
well simply use
<asp:Button ID="btnSave" runat="server" class="btn btn-active" OnClick="btnSave_Click" ValidationGroup="validation" Text="Save" OnClientClick="if (!Page_ClientValidate()){ return false; } this.disabled = true; this.value = 'Saving...';"
UseSubmitBehavior="false" />
This code snippet will disable your button and doesn't allow use to click multiple times until click event executing its code
Hope this will help :)
If you do not want duplicates, why not check them at the database level? Disabling a button will help with double clicking. But you will still get the same result if a user presses F5 or reloads the page as new and then presses the button again.
For MS SQL you could do something like this:
IF NOT EXISTS (SELECT column FROM table WHERE (column = #myVar))
INSERT INTO table (column) VALUES (#myVar)
Or you could also place a constraint on the column
ALTER TABLE table ADD CONSTRAINT UQ_column UNIQUE (column)
you can do this $(document).ready(function(){
$('#ctl00_MainContent_btnSave')
.attr("onclick", null)
.removeAttr("onclick")
.click(function() {
// To validate you form using Validation group.
if (typeof (Page_ClientValidate) == 'function') {
Page_ClientValidate("ValidationGroup");
if (Page_IsValid == true) {
alert('the form is valid');
}
} else {
if ($(this).valid()) {
alert('the form is valid');
}
}
//Disable button before page posting back
WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions($(this).attr("name"), "", true, "", "", false, false));
});
});
I figured it out. When i used code #Shayan Hafeez provided, compiler thrown an exception.
The server tag is not well formed.
Than, i removed OnClientClick from the button and insert this code into code-behind :
btnSave.ClientSideEvents.Click = "if (!Page_ClientValidate()){ return false; } this.disabled = true; this.value = 'Saving...';";
It works fine now.

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) + ";");

ASP OnText event based controlling button control

What I'm trying to do is has a specific button enables or disables based on the number of characters that have been imputed into a textbox.
The event only fire when I click off the textbox, maybe i'm looking for something else?
<telerik:RadTextBox ID="InputVinInformationTextBox" runat="server"
Skin="Office2010Blue"
Width="250px"
MaxLength="16"
OnTextChanged="InputVinInformationTextBox_OnText"
AutoPostBack="true">
</telerik:RadTextBox>
protected void InputVinInformationTextBox_OnText(object sender, EventArgs e)
{
if (InputVinInformationTextBox.Text.Length >= 8)
{
VinSubmitButton.Enabled = true;
}
else
{
VinSubmitButton.Enabled = false;
}
}
If you don't mind using jQuery you could remove the OnTextChanged function and instead bind the functionality to the keyup event. All you need to do is to add the following in your <head> tag:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function() {
$("#<%=InputVinInformationTextBox.ClientID%>").keyup(function() {
if (InputVinInformationTextBox.Text.Length >= 8)
{
VinSubmitButton.Enabled = true;
}
else
{
VinSubmitButton.Enabled = false;
}
}
});
</script>
I'm not sure what your VinSubmitButton is, but I assume, since it was working in your example, that that is an element that you already have stored.
This behavior is by design:
All RadInput controls provide the TextChanged server event, which is
raised when the AutoPostBack property is set to true, the user types
valid entry, and the input loses focus.
The TextChanged event only occurs if the value of the input control
actually changes. If the user changes the string in the input control
but does not actually change the value...the TextChanged event does
not occur.
See this help topic on Telerik's site for more info.
I recommend using the OnTextChanged event as you have been, as it will only fire when valid text is entered that changes the previous value of the RadTextBox.
Alternatively, you can use JavaScript to determine when an appropriate number of characters have been entered, then trigger the request manually.
<telerik:RadTextBox ID="InputVinInformationTextBox" runat="server"
Skin="Office2010Blue"
Width="250px"
MaxLength="16"
OnLoad="InputVinInformationTextBox_OnLoad">
<ClientEvents OnKeyPress="InputVinInformationTextBox_OnKeyPress" />
</telerik:RadTextBox>
<script type="text/javascript">
function InputVinInformationTextBox_OnKeyPress(sender, args) {
var text = sender.get_value();
if (text.length >= 8) {
var ajaxManager = $find('<%= RadAjaxManager.GetCurrent(Page) %>');
ajaxManager.ajaxRequestWithTarget(sender.get_id(), '');
}
}
</script>
The code above assumes you are also using a RadAjaxManager on the page and that it has been configured to update all/part of the page when triggered by the RadTextBox. You'd need to check the RadTextBox value during the OnLoad event of the control (or later) so that all ViewState and form values have been initialized for the control.
protected void InputVinInformationTextBox_OnLoad(object sender, EventArgs e)
{
if (InputVinInformationTextBox.Text.Length >= 8)
{
VinSubmitButton.Enabled = true;
}
else
{
VinSubmitButton.Enabled = false;
}
}

How to capture 'Update' click event in ASP.NET GridView with jQuery

I need to capture the 'Update' click event with jQuery in an asp.net GridView and have no way of knowing where to start. I'm still rather new to jQuery. My GridView is attached to a SQLDataSource and, naturally, has all the bells and whistles that that combination affords. Any help would be greatly appreciated.
Simply add the script block anywhere after the GridView is declared and it should work with the default non-templated GridView column. No code in the codebehind as it is purely a Javascript solution.
Use this if you are using a Link-type GridView column:
<script type="text/javascript">
// a:contains(The text of the link here)
$('#<%= theGridViewID.ClientID %> a:contains(Update)').click(function () {
alert('Update click event captured from the link!');
// return false: stop the postback from happening
// return true or don't return anything: continue with the postback
});
</script>
Use this if you are using a Button-type GridView column and you don't want your Javascript to block the postback:
<script type="text/javascript">
// :button[value=The text of the button here]
$('#<%= theGridViewID.ClientID %> :button[value=Update]').click(function () {
alert('Update click event captured from the button!');
});
</script>
Use this if you are using a Button-type GridView column and you want to have control whether to continue with the postback or not:
<script type="text/javascript">
// :button[value=The text of the button here]
var updateButtons = $('#<%= theGridViewID.ClientID %> :button[value=Update]');
updateButtons
.attr('onclick', null)
.click(function () {
alert('Update click event captured from the button!');
var doPostBack = true; // decide whether to do postback or not
if (doPostBack) {
var index = updateButtons.index($(this));
// 'Update$' refers to the GridView command name + dollar sign
__doPostBack('<%= theGridViewID.UniqueID %>', 'Update$' + index);
}
});
</script>
Update: I think this would be a better solution in replacement of the last (3rd) script block I presented above, since you won't need to update the __doPostBack function call manually based on the command name, and as such, it should be less error-prone:
<script type="text/javascript">
// :button[value=The text of the button here]
var updateButtons = $('#<%= theGridViewID.ClientID %> :button[value=Update]');
updateButtons.each(function () {
var onclick = $(this).attr('onclick');
$(this).attr('onclick', null).click(function () {
alert('Update click event captured from the button!');
var doPostBack = true; // decide whether to do postback or not
if (doPostBack) {
onclick();
}
});
});
</script>
Credit to Aristos for this idea. :)
Ok here is my solution to capture only one update (or more) from a button.
This is the javascript code that I run on update click
<script type="text/javascript">
function NowRunTheUpdate(){
alert("ok I capture you");
}
</script>
and here is the page code
`<asp:GridView ID="MyGridView" runat="server" OnRowDataBound="MyGridView_RowDataBound" ... >`
<asp:ButtonField Text="update" CommandName="Update" ButtonType="Button" />
...
Here is the code thats run behind and set the javascript.
protected void MyGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// loop all data rows
foreach (DataControlFieldCell cell in e.Row.Cells)
{
// check all cells in one row
foreach (Control control in cell.Controls)
{
// I go to get the button if exist
Button button = control as Button;
if (button != null && button.CommandName == "Update")
// Add delete confirmation
button.OnClientClick = "NowRunTheUpdate();";
}
}
}
}
You need to attach a client-side event listener to the click event of the Update [link]button. I don't think it can be done using AutoGenerateEditButton="true" if you are doing it that way. You'll need to use a TemplateField so that you can manipulate the button. Then you can use jQuery to bind to the click event of the button.
Add the update column to the column templates. Convert it to a custom column, and modify it in such a way you can hook to it with jquery i.e. like adding a css class to it.
Gridview is nothing but a table with a bunch of "tr" and "td". If you understand that concept then it would be easy for you to handle anything at client side. If you have enabled auto everything then it will be a link which would result for Edit, Delete, Update or Cancel (Check View Source). The code given below should capture the update click event:
$("a:contains(Update)").live("click", function() {
//alert("hi"); do what needs to be done
return false;//would not sent the control back to server
});
HTH

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.

Resources